Hi I am new to Retrofit framework for Android. I could get JSON responses from REST services using it but I don't know how to fetch a image using retrofit2. I am trying to fetch the image in recyclerview from the database
Code is Here:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_product);
Intent intent = getIntent();
parent = intent.getStringExtra("Parent");
child = intent.getStringExtra("Child");
Toast.makeText(this, parent+child, Toast.LENGTH_SHORT).show();
//init firebase
//load menu
recycler_menu =(RecyclerView)findViewById(R.id.recycler_view);
apiInterface =
ApiClient.getRetrofit().create(ApiInterface.class);
recycler_menu.setLayoutManager(new GridLayoutManager(this, 2));
recycler_menu.setHasFixedSize(true);
mUploads = new ArrayList<>();
loadMenu();
}
private void loadMenu(){
Toast.makeText(Product.this, "Hello",
Toast.LENGTH_SHORT).show();
Call<Upload> call = apiInterface.performProduct(parent,child);
call.enqueue(new Callback<Upload>() {
#Override
public void onResponse(Call<Upload> call, Response<Upload>
response) {
Toast.makeText(Product.this, "Hello", Toast.LENGTH_SHORT).show();
mAdapter = new ImageAdapter(Product.this, mUploads);
mRecyclerView.setAdapter(mAdapter);
}
#Override
public void onFailure(Call<Upload> call, Throwable t) {
}
});
}}
ImageAdapter.java .
public ImageAdapter(Context context, List<Upload> uploads) {
mContext = context;
mUploads = uploads;
}
#Override
public ImageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(mContext).inflate(R.layout.image_item, parent, false);
return new ImageViewHolder(v);
}
#Override
public void onBindViewHolder(ImageViewHolder holder, int position) {
Upload uploadCurrent = mUploads.get(position);
holder.textViewName.setText(uploadCurrent.getImgName());
holder.textViewPrice.setText(uploadCurrent.getPrice());
Picasso.get()
.load(uploadCurrent.getImgUrl())
.placeholder(R.mipmap.ic_launcher)
.fit()
.centerCrop()
.into(holder.imageView);
//holder.collection.setText(uploadCurrent.getmRadioGroup());
}
#Override
public int getItemCount() {
return mUploads.size();
}
public class ImageViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener,
View.OnCreateContextMenuListener {
public TextView textViewName;
public TextView textViewPrice;
public ImageView imageView;
public ImageViewHolder(View itemView) {
super(itemView);
textViewName = itemView.findViewById(R.id.menu_name);
textViewPrice = itemView.findViewById(R.id.menu_price);
imageView = itemView.findViewById(R.id.menu_price);
itemView.setOnClickListener(this);
itemView.setOnCreateContextMenuListener(this);
}
#Override
public void onClick(View v) {
if (mListener != null) {
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION) {
mListener.onItemClick(position);
}
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
menu.setHeaderTitle("Select Action");
MenuItem doWhatever = menu.add(Menu.NONE, 1, 1, "Do whatever");
MenuItem delete = menu.add(Menu.NONE, 2, 2, "Delete");
}
}
public interface OnItemClickListener {
void onItemClick(int position);
}
public void setOnItemClickListener(OnItemClickListener listener) {
mListener = listener;
}
Upload.class
public class Upload {
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
#SerializedName("id")
private String id;
#SerializedName("image")
private String imgName;
#SerializedName("imgUrl")
private String imgUrl;
#SerializedName("price")
private String price;
#SerializedName("description")
private String Description;
#SerializedName("response")
private String Response;
public String getResponse(){
return Response;
}
public Upload() {
}
public Upload(String id,String imgName, String imgUrl, String price, String Description) {
this.id = id;
this.imgName = imgName;
this.imgUrl = imgUrl;
this.price = price;
this.Description = Description;
}
public String getImgName() {
return imgName;
}
public void setImgName(String imgName) {
this.imgName = imgName;
}
public String getImgUrl() {
return imgUrl;
}
public void setImgUrl(String imgUrl) {
this.imgUrl = imgUrl;
}
public String getDescription() {
return Description;
}
public void setDescription(String Description) {
this.Description = Description;
}
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
}
PHP File:
<?php include ("conn.php");
$type = $_GET["parent"];
$ttype = $_GET["child"];
$sth = $conn->prepare("SELECT * from product where type='$type' &&
s_type='$ttype'");
$sth->execute();
While ($data = $sth->fetch(PDO::FETCH_ASSOC)){
$name = $data['name'];
$id = $data['id'];
$des = $data['description'];
$price = $data['price'];
$image = $data['image'];
$status = "ok";
echo
json_encode(array("response"=>$status,
"img"=>$image,"name"=>$name,
"id"=>$id,"description"=>$des,"price"=>$price));
}?>
this code does nothing a blank screen appers
You are sending blank ArrayList to Adapter
look here In onCreate() you assign mUploads = new ArrayList<>();
then you just pass mUploads to mAdapter = new ImageAdapter(Product.this, mUploads);
chnage code from
#Override
public void onResponse(Call<Upload> call, Response<Upload>
response) {
Toast.makeText(Product.this, "Hello", Toast.LENGTH_SHORT).show();
mAdapter = new ImageAdapter(Product.this, mUploads);
mRecyclerView.setAdapter(mAdapter);
}
to ,
#Override
public void onResponse(Call<Upload> call, Response<Upload>
response) {
Toast.makeText(Product.this, "Hello", Toast.LENGTH_SHORT).show();
mUploads=responese.body(); //# add this line
mAdapter = new ImageAdapter(Product.this, mUploads);
mRecyclerView.setAdapter(mAdapter);
}
From your endpoint I got the following response
{"response":"ok","img":"greypant.jpg","name":"GreyPant","id":"1","description":"A very fine pant with great finishing.","price":"1500"}
you can try making the following edits to your PHP file to get the full path to the image file(s).
<?php
include ("conn.php");
$type = $_GET["parent"];
$ttype = $_GET["child"];
$sth = $conn->prepare("SELECT * from product where type='$type' &&
s_type='$ttype'");
$sth->execute();
While ($data = $sth->fetch(PDO::FETCH_ASSOC)){
$name = $data['name'];
$id = $data['id'];
$des = $data['description'];
$price = $data['price'];
$image = $data['image'];
$status = "ok";
echo json_encode(array("response"=>$status,
"img"=> "http://yourdomain.com/{$image}",
"name"=>$name,
"id"=>$id,
"description"=>$des,
"price"=>$price));
}
?>
replace http://yourdomain.com/ with the full path to the directory where your image is saved. Good luck!
Related
and thank you for your attention to my request.
I'm a newbie on Andorid Studio and I'm developing an App, it has to show a list of Events, Courses and News. There is a DrawerLayout which allow navigating into Event's, course's and news's area, each area has each specific RecyclerView, but into the home activity, I have to show all the items (Event, Course and News).
I create an Adapter for each item (because they have different properties) and each section (fragment) works properly but now I'm stuck with the main activity (the home).
Here are the models for explaining the difference between them:
Event
public class Event {
private int id;
private String title;
private String description;
private LocalDateTime startingDate;
private LocalDateTime endingDate;
private String cost;
private String website;
private Category category;
private Venue venue;
private Organizer organizer;
private String status;
private int resImage;
public Event(int id, String title, String description, LocalDateTime startingDate, LocalDateTime endingDate, String cost, String website, Category category, Venue venue, Organizer organizer, int image) {
this.id = id;
this.title = title;
this.description = description;
this.startingDate = startingDate;
this.endingDate = endingDate;
this.cost = cost;
this.website = website;
this.category = category;
this.venue = venue;
this.organizer = organizer;
this.resImage = image;
}
public Event(){}
public int getId() {
return id;
}
public String getTitle() {
return title;
}
public void setTitle(String name) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public LocalDateTime getStartingDate() {
return startingDate;
}
public void setStartingDate(LocalDateTime startingDate) {
this.startingDate = startingDate;
}
public LocalDateTime getEndingDate() {
return endingDate;
}
public void setEndingDate(LocalDateTime endingDate) {
this.endingDate = endingDate;
}
public String getCost() {
return cost;
}
public void setCost(String cost) {
this.cost = cost;
}
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public Category getCategory() {
return category;
}
public Venue getVenue() {
return venue;
}
public Organizer getOrganizer() {
return organizer;
}
public String getStatus() {
return status;
}
public int getResImage() {
return resImage;
}
}
News:
public class News {
private int id;
private String title;
private String content;
private int resImage;
public News(int id, String title, String content, int image) {
this.id = id;
this.title = title;
this.content = content;
this.resImage = image;
}
public News(){}
public int getId(){
return this.id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setDescription(String description) {
this.content = content;
}
public int getResImage() {
return resImage;
}
public void setResImage(int resImage) {
this.resImage = resImage;
}
}
Courses
public Course(int id, String title, String content, float price, LocalDate startingDate, int availablePlace, Teacher teacher, CourseCategory courseCategory, Location location, Duration duration, Level level, int resImage) {
this.id = id;
this.title = title;
this.content = content;
this.price = price;
this.startingDate = startingDate;
this.availablePlace = availablePlace;
this.teacher = teacher;
this.courseCategory = courseCategory;
this.location = location;
this.duration = duration;
this.level = level;
this.resImage = resImage;
}
public int getId() {
return id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public LocalDate getStartingDate() {
return startingDate;
}
public void setStartingDate(LocalDate startingDate) {
this.startingDate = startingDate;
}
public int getAvailablePlace() {
return availablePlace;
}
public void setAvailablePlace(int availablePlace) {
this.availablePlace = availablePlace;
}
public Teacher getTeacher() {
return teacher;
}
public void setTeacher(Teacher teacher) {
this.teacher = teacher;
}
public CourseCategory getCourseCategory() {
return courseCategory;
}
public void setCourseCategory(CourseCategory courseCategory) {
this.courseCategory = courseCategory;
}
public Location getLocation() {
return location;
}
public void setLocation(Location location) {
this.location = location;
}
public Duration getDuration() {
return duration;
}
public void setDuration(Duration duration) {
this.duration = duration;
}
public Level getLevel() {
return level;
}
public int getResImage() {
return resImage;
}
public void setResImage(int resImage) {
this.resImage = resImage;
}
}
Here is the Adapters:
EventAdapter
public class EventViewAdapter extends RecyclerView.Adapter<EventViewAdapter.EventViewHolder> {
ArrayList<Event> eventList;
Context context;
public EventViewAdapter(ArrayList<Event> eventList, Context context) {
this.eventList = eventList;
this.context = context;
}
public EventViewAdapter() {
}
public static class EventViewHolder extends RecyclerView.ViewHolder {
ImageView eventImage;
TextView startingDate, place, title;
LinearLayout cellLayout;
EventViewHolder(View eventView) {
super(eventView);
eventImage = eventView.findViewById(R.id.event_image);
startingDate = eventView.findViewById(R.id.event_starting_date);
place = eventView.findViewById(R.id.event_place);
title = eventView.findViewById(R.id.event_title);
cellLayout = eventView.findViewById(R.id.event_cell_layout);
}
}
#NonNull
#Override
public EventViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.event_cell_def, parent, false);
EventViewHolder evh = new EventViewHolder(view);
return evh;
}
#Override
public void onBindViewHolder(#NonNull EventViewHolder holder, int position) {
final String title = eventList.get(position).getTitle();
final String description = eventList.get(position).getDescription();
final String place = eventList.get(position).getVenue().getCity();
final String address = eventList.get(position).getVenue().getAddress();
final String startDate = String.valueOf(eventList.get(position).getStartingDate().toLocalDate());
final String startTime = String.valueOf(eventList.get(position).getStartingDate().getHour() + ":" + String.valueOf(eventList.get(position).getStartingDate().getMinute()));
final String endDate = String.valueOf(eventList.get(position).getEndingDate().toLocalDate());
final String cost = eventList.get(position).getCost();
final String website = eventList.get(position).getWebsite();
final String category = eventList.get(position).getCategory().getName();
final String organizer = eventList.get(position).getOrganizer().getOrganizer();
final String organizerWebsite = eventList.get(position).getOrganizer().getWebsite();
final int image = eventList.get(position).getResImage();
holder.eventImage.setImageResource(image);
holder.startingDate.setText(startDate);
holder.place.setText(place);
holder.title.setText(title);
holder.cellLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), DetailEventActivity.class);
intent.putExtra("title", title);
intent.putExtra("description", description);
intent.putExtra("place", place);
intent.putExtra("address", address);
intent.putExtra("startDate", startDate);
intent.putExtra("startTime", startTime);
intent.putExtra("endDate", endDate);
intent.putExtra("cost", cost);
intent.putExtra("website", website);
intent.putExtra("category", category);
intent.putExtra("organizer", organizer);
intent.putExtra("orgWebsite", organizerWebsite);
intent.putExtra("image", image);
v.getContext().startActivity(intent);
Toast.makeText(context, "Hai premuto su: " + title, Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return eventList.size();
}
public void eventSetSearchOperation(ArrayList<Event> newList){
eventList = new ArrayList<>();
eventList.addAll(newList);
notifyDataSetChanged();
}
}
CourseAdapter:
public class CourseViewAdapter extends RecyclerView.Adapter<CourseViewAdapter.CourseViewHolder> {
ArrayList<Course> courseList;
Context context;
public CourseViewAdapter(ArrayList<Course> courseList, Context context) {
this.courseList = courseList;
this.context = context;
}
public CourseViewAdapter(){}
public static class CourseViewHolder extends RecyclerView.ViewHolder {
ImageView courseImage;
TextView startingDate, place, title;
LinearLayout courseLinear;
CourseViewHolder(View courseView){
super(courseView);
courseImage = courseView.findViewById(R.id.course_image);
startingDate = courseView.findViewById(R.id.course_starting_date);
place = courseView.findViewById(R.id.course_place);
title = courseView.findViewById(R.id.course_title);
courseLinear = courseView.findViewById(R.id.course_cell_layout);
}
}
#NonNull
#Override
public CourseViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.course_cell_def, parent, false);
CourseViewHolder cvh = new CourseViewHolder(view);
return cvh;
}
#Override
public void onBindViewHolder(#NonNull CourseViewHolder holder, int position) {
final String title = courseList.get(position).getTitle();
final String category = courseList.get(position).getCourseCategory().getName();
final String description = courseList.get(position).getContent();
final String place = courseList.get(position).getLocation().getName();
final String startDate = String.valueOf(courseList.get(position).getStartingDate());
final int availablePlace = courseList.get(position).getAvailablePlace();
final String teacher = courseList.get(position).getTeacher().getName();
final String teacherEmail = courseList.get(position).getTeacher().getEmail();
final String teacherMobile = courseList.get(position).getTeacher().getPhone();
final String duration = courseList.get(position).getDuration().getName();
final String level = courseList.get(position).getLevel().getName();
final String price = String.valueOf(courseList.get(position).getPrice());
final int image = courseList.get(position).getResImage();
holder.courseImage.setImageResource(image);
holder.startingDate.setText(startDate);
holder.place.setText(place);
holder.title.setText(title);
holder.courseLinear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), DetailCourseActivity.class);
intent.putExtra("title", title);
intent.putExtra("category", category);
intent.putExtra("content", description);
intent.putExtra("startDate", startDate);
intent.putExtra("availablePlace", availablePlace);
intent.putExtra("teacher", teacher);
intent.putExtra("teacherEmail", teacherEmail);
intent.putExtra("teacherMobile", teacherMobile);
intent.putExtra("duration", duration);
intent.putExtra("price", price);
intent.putExtra("place", place);
intent.putExtra("level", level);
intent.putExtra("image", image);
v.getContext().startActivity(intent);
Toast.makeText(context, "Hai premuto su: " + title, Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return courseList.size();
}
public void courseSetSearchOperation(ArrayList<Course> newList){
courseList = new ArrayList<>();
courseList.addAll(newList);
notifyDataSetChanged();
}
}
News:
public class NewsViewAdapter extends RecyclerView.Adapter<NewsViewAdapter.NewsViewHolder> {
ArrayList<News> newsList;
Context context;
public NewsViewAdapter(ArrayList<News> newsList, Context context) {
this.newsList = newsList;
this.context = context;
}
public NewsViewAdapter(){}
public static class NewsViewHolder extends RecyclerView.ViewHolder {
ImageView newsImage;
TextView newsTitle, newsContent;
LinearLayout newsLayout;
NewsViewHolder(View newView){
super(newView);
newsImage = newView.findViewById(R.id.news_image);
newsTitle = newView.findViewById(R.id.news_title);
newsContent = newView.findViewById(R.id.news_content);
newsLayout = newView.findViewById(R.id.news_cell_layout);
}
}
#NonNull
#Override
public NewsViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.news_cell_def, parent, false);
NewsViewHolder nvh = new NewsViewHolder(view);
return nvh;
}
#Override
public void onBindViewHolder(#NonNull NewsViewHolder holder, int position) {
final String title = newsList.get(position).getTitle();
final String content = newsList.get(position).getContent();
final int image = newsList.get(position).getResImage();
holder.newsImage.setImageResource(image);
holder.newsTitle.setText(title);
holder.newsContent.setText(content);
holder.newsLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), DetailNewsActivity.class);
intent.putExtra("title", title);
intent.putExtra("content", content);
intent.putExtra("image", image);
v.getContext().startActivity(intent);
Toast.makeText(context, "Premuto su: " + title, Toast.LENGTH_SHORT).show();
}
});
}
#Override
public int getItemCount() {
return newsList.size();
}
public void newsSetSearchOperation(ArrayList<News> newList){
newsList = new ArrayList<>();
newsList.addAll(newList);
notifyDataSetChanged();
}
}
Each specific list of item is into a fragment, indeed here is the Main Activity (home), where I would like to display a RecyclerView of all the itmes:
public class MainActivity extends AppCompatActivity {
private DrawerLayout drawerLayout;
private NavigationView mNavigationView;
private Toolbar toolbar;
private ActionBarDrawerToggle drawerToggle;
private FloatingActionButton fab;
private RecyclerView mRecyclerView;
private ImageView openFilter;
private SearchView searchView;
private DataMock dataMock = new DataMock();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mRecyclerView = findViewById(R.id.recycler_view_main);
drawerLayout = findViewById(R.id.drawer_layout);
mNavigationView = findViewById(R.id.nav_view);
toolbar = findViewById(R.id.toolbar);
openFilter = findViewById(R.id.filter_icon);
searchView = findViewById(R.id.action_search);
fab = findViewById(R.id.fab);
fab.show();
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
searchView.setQueryHint(getString(R.string.search_hint));
drawerToggle = setupDrawerToggle();
drawerToggle.setDrawerIndicatorEnabled(true);
drawerToggle.syncState();
drawerLayout.setDrawerListener(drawerToggle);
drawerLayout.setDrawerListener(new DrawerLayout.SimpleDrawerListener() {
#Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
#Override
public void onDrawerClosed(View drawerView) {
super.onDrawerClosed(drawerView);
}
});
mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(#NonNull MenuItem menuItem) {
Fragment nextFragment;
switch (menuItem.getItemId()){
case R.id.event_list:
nextFragment = new EventFragment();
break;
case R.id.course_list:
nextFragment = new CourseFragment();
break;
case R.id.news_list:
nextFragment = new NewsFragment();
break;
default:
throw new IllegalArgumentException("No Fragment for the given menu item");
}
if (nextFragment != null){
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.anchor_point, nextFragment)
.commit();
menuItem.setChecked(true);
setTitle(menuItem.getTitle());
drawerLayout.closeDrawer(mNavigationView);
}
return false;
}
});
openFilter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
BottomSheetDialog filterDialog = new BottomSheetDialog();
filterDialog.show(getSupportFragmentManager(), "filter dialog opened!");
}
});
// mRecyclerView.setHasFixedSize(true);
// LinearLayoutManager layoutManager = new LinearLayoutManager(this);
// mRecyclerView.setLayoutManager(layoutManager);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
switch (item.getItemId()) {
case android.R.id.home:
drawerLayout.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
private ActionBarDrawerToggle setupDrawerToggle() {
// NOTE: Make sure you pass in a valid toolbar reference. ActionBarDrawToggle() does not require it
// and will not render the hamburger icon without it.
return new ActionBarDrawerToggle(this, drawerLayout, toolbar, R.string.drawer_open, R.string.drawer_close);
}
public void backToHome(View view){
for (Fragment fragment : getSupportFragmentManager().getFragments()){
if (fragment != null && (fragment instanceof CourseFragment || fragment instanceof EventFragment || fragment instanceof NewsFragment)){
getSupportFragmentManager().beginTransaction().remove(fragment).commit();
toolbar.setTitle("WePress");
fab.show();
}
}
Toast.makeText(this, "Premuto sul logo", Toast.LENGTH_SHORT).show();
drawerLayout.closeDrawer(mNavigationView);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggles
drawerToggle.onConfigurationChanged(newConfig);
}
public void addItem(View view){
PopupMenu popupMenu = new PopupMenu(MainActivity.this, fab);
popupMenu.getMenuInflater().inflate(R.menu.fab_main_menu, popupMenu.getMenu());
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()){
case R.id.add_event:
Toast.makeText(MainActivity.this, "Pronti per aggiungere un evento", Toast.LENGTH_SHORT).show();
Intent intentEvent = new Intent(MainActivity.this, AddItemActivity.class);
intentEvent.putExtra("isFrom", "event");
startActivity(intentEvent);
break;
case R.id.add_course:
Toast.makeText(MainActivity.this, "Pronti per aggiungere un corso", Toast.LENGTH_SHORT).show();
Intent intentCourse = new Intent(MainActivity.this, AddItemActivity.class);
intentCourse.putExtra("isFrom", "course");
startActivity(intentCourse);
break;
case R.id.add_news:
Toast.makeText(MainActivity.this, "Pronti per aggiungere una news", Toast.LENGTH_SHORT).show();
Intent intentNews = new Intent(MainActivity.this, AddItemActivity.class);
intentNews.putExtra("isFrom", "news");
startActivity(intentNews);
break;
}
return true;
}
});
popupMenu.show();
}
}
if it's possible to show the list with differents layouts, can you also suggest a way to improve the quality of my code avoiding to repeat lines of code? If I'm not wrong, I would like to re-use each Adapter or part of them that I can put into a specific class (?).
Thank you so much for your help!
If I'm missing some information, please ask me in order to edit the post.
You must do only one adapter (using view type) with a view model class
that contain either an event or a news or a course
the adapter should be something like that:
public class EventViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
private static final int TYPE_EVENT = 10;
private static final int TYPE_COURSE = 11;
private static final int TYPE_NEWS = 12;
ArrayList<EventViewModel> eventList;
Context context;
public EventViewAdapter(ArrayList<EventViewModel> eventList, Context context) {
this.eventList = eventList;
this.context = context;
}
public EventViewAdapter() {
}
#Override
public int getItemViewType(int position) {
EventViewModel event = eventList.get(position);
if (event.isEvent()) {
return TYPE_EVENT ;
} else if(event.isCourse()) {
return TYPE_COURSE;
} else {
return TYPE_NEWS;
}
}
public static class EventViewHolder extends RecyclerView.ViewHolder {
ImageView eventImage;
//....
EventViewHolder(View eventView) {
super(eventView);
eventImage = eventView.findViewById(R.id.event_image);
//.....
}
}
public static class CourseViewHolder extends RecyclerView.ViewHolder {
ImageView courseImage;
//.....
CourseViewHolder(View courseView) {
super(courseView);
courseImage = courseView.findViewById(R.id.course_image);
//.....
}
public static class NewsViewHolder extends RecyclerView.ViewHolder {
ImageView newsImage;
//.....
NewsViewHolder(View newView){
super(newView);
newsImage = newView.findViewById(R.id.news_image);
//.....
}
#NonNull
#Override
public RecyclerView.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
if (viewType == TYPE_EVENT) {
View rootView = LayoutInflater.from(parent.getContext()).inflate(R.layout.event_cell_def, parent, false);
return new EventViewHolder (rootView);
} else if (viewType == TYPE_COURSE) {
View rootView = LayoutInflater.from(parent.getContext()).inflate(R.layout.course_cell_def, parent, false);
return new CourseViewHolder(rootView);
} else {
View rootView = LayoutInflater.from(parent.getContext()).inflate(R.layout.news_cell_def, parent, false);
return new NewsViewHolder(rootView);
}
}
#Override
public void onBindViewHolder(#NonNull EventViewHolder holder, int position)
{
final EventViewModel eventViewModel = eventList.get(position);
if (eventViewModel .isEvent()) {
onBindEvent(holder, eventViewModel.getEvent());
} else if(eventViewModel .isCourse()) {
onBindCourse(holder, eventViewModel.getCourse());
} else {
onBindNews(holder, eventViewModel.getNews());
}
}
private void onBindEvent(RecyclerView.ViewHolder holder, Event event) {
EventViewHolder eventHolder= (EventViewHolder ) holder;
final String title = event.getTitle();
final String description = event.getDescription();
// others ...
holder.eventImage.setImageResource(image);
holder.startingDate.setText(startDate);
// others ...
holder.cellLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
// ...
}
#Override
public int getItemCount() {
return eventList.size();
}
public void eventSetSearchOperation(ArrayList<Event> newList){
eventList = new ArrayList<>();
eventList.addAll(newList);
notifyDataSetChanged();
}
}
And a View Model classes like that :
public class EventViewModel() {
private Event mEvent;
private Course mCourse;
private News mNews;
private EventViewModel(Event event, Course course, News news) {
this.mEvent = event;
this.mCourse = course;
this.mNews = news;
}
public boolean isEvent() {
return mEvent != null
}
public boolean isCourse() {
return mCourse != null
}
public boolean isNews() {
return mNews != null
}
public static EventViewModel getEventInstance(Event event) {
return new EventViewModel(event, null, null
}
public static EventViewModel getCourseInstance(Course course) {
return new EventViewModel(null, course, null
}
public static EventViewModel getNewsInstance(News news) {
return new EventViewModel(null, null, news
}
public Event getEvent() {
return mEvent;
}
public Event getCourse() {
return mScore;
}
public Event getNews() {
return mNews;
}
}
You can use this adapter in all of your fragments (event, course, news) and each fragment contaions a list of EventViewModel with only its specific type. The adapter display in the main activity contains EventViewModel of all types to display all events.
I'm implementing my small app. Today,
I'm having trouble getting data from my Firebase.
Here is my Firebase structure:
This is modal Request:
public class Request {
// private String phone, name, address, total, status;
private String phone, name, address, status;
private int total;
private List<Order> foods;
public Request() {
}
public Request(String phone, String name, String address, int total, List<Order> foods) {
this.phone = phone;
this.name = name;
this.address = address;
this.total = total;
this.foods = foods;
this.status = "0"; //Default 0. 0: place, 1: shipping, 2: shipped
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public List<Order> getFoods() {
return foods;
}
public void setFoods(List<Order> foods) {
this.foods = foods;
}
}
I obtained the Order data by going to "PhoneNumber" and getting the
"ID Order" data as follows:
private FirebaseRecyclerAdapter<Request, OrderViewHolder> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order_status);
//Firebase:
FirebaseDatabase database = FirebaseDatabase.getInstance();
requests = database.getReference("Requests");
//init:
recyclerView = (RecyclerView) findViewById(R.id.recycler_orderview);
recyclerView.setHasFixedSize(true);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
loadOrders(Common.currentUser.getPhone());
//Common.currentUser.getPhone() This is PhoneNumber current
}
private void loadOrders(final String phone) {
adapter = new FirebaseRecyclerAdapter<Request, OrderViewHolder>(
Request.class,
R.layout.order_item,
OrderViewHolder.class,
requests.child(phone) // I have access to "PhoneNumber"
) {
#Override
protected void populateViewHolder(OrderViewHolder viewHolder, Request model, int position) {
viewHolder.txtOrderId.setText(adapter.getRef(position).getKey());
viewHolder.txtOrderStatus.setText(convertCodeToStatus(model.getStatus()));
viewHolder.txtOrderPhone.setText(model.getPhone());
viewHolder.txtOrderAddress.setText(model.getAddress());
viewHolder.txtOrderTotal.setText(String.valueOf(model.getTotal()));
viewHolder.setItemClickListener(new ItemClickListener() {
#Override
public void onClick(View view, int position, boolean isLongClick) {
// Get CategoryID and send Activity Foods List:
Intent moveToOrderDetails = new Intent(OrderStatusActivity.this, OrderDetailsActivity.class);
moveToOrderDetails.putExtra("KeyOrder", adapter.getRef(position).getKey());
startActivity(moveToOrderDetails);
}
});
}
};
adapter.notifyDataSetChanged();
recyclerView.setAdapter(adapter);
}
And this is my Apdapter:
public class OrderViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener, View.OnCreateContextMenuListener {
public TextView txtOrderId, txtOrderStatus, txtOrderPhone, txtOrderAddress, txtOrderTotal;
private ItemClickListener itemClickListener;
public OrderViewHolder(View itemView) {
super(itemView);
txtOrderId = (TextView) itemView.findViewById(R.id.order_id);
txtOrderStatus = (TextView) itemView.findViewById(R.id.order_status);
txtOrderPhone = (TextView) itemView.findViewById(R.id.order_phone);
txtOrderAddress = (TextView) itemView.findViewById(R.id.order_address);
txtOrderTotal = (TextView) itemView.findViewById(R.id.order_total);
itemView.setOnClickListener(this);
itemView.setOnCreateContextMenuListener(this);
}
public void setItemClickListener(ItemClickListener itemClickListener) {
this.itemClickListener = itemClickListener;
}
#Override
public void onClick(View view) {
itemClickListener.onClick(view,getAdapterPosition(),false);
}
#Override
public void onCreateContextMenu(ContextMenu contextMenu, View view, ContextMenu.ContextMenuInfo contextMenuInfo) {
contextMenu.setHeaderTitle("Select the action");
contextMenu.add(0, 0, getAdapterPosition(), Common.UPDATE);
contextMenu.add(0, 1, getAdapterPosition(), Common.DELETE);
}
}
And now I'm having trouble figuring out how to get the data of all
orders without having to go to "Number Phone". I tried to think and
perform but failed.
This is image demo about an order:
I have list of data in MenuItemsModel(model) class along with image url and two strings fetching from the API. How can I load the image url with Picasso and how to bind the loaded image to recyclerview?
Here is my code
Code for model class
public class MenuItemsModel {
public int image;
public String itemName;
public String itemCost;
public MenuItemsModel(int image, String itemName, String itemCost) {
this.image = image;
this.itemName = itemName;
this.itemCost = itemCost;
}
public int getImage() {
return image;
}
public void setImage(int image) {
this.image = image;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public String getItemCost() {
return itemCost;
}
public void setItemCost(String itemCost) {
this.itemCost = itemCost;
}
}
Here is my RecyclerAdapter class
public class MenusRecyclearView extends
RecyclerView.Adapter<MenusRecyclearView.RecyclerViewHolder> {
Context context;
List<MenuItemsModel> menuItemsModel;
public MenusRecyclearView(Context context, List<MenuItemsModel> menuItemsModel) {
this.context = context;
this.menuItemsModel = menuItemsModel;
}
#Override
public RecyclerViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.menu_items_list, parent, false);
return new RecyclerViewHolder(view, context, menuItemsModel);
}
#Override
public void onBindViewHolder(RecyclerViewHolder holder, int position) {
holder.imageView.setImageResource(menuItemsModel.get(position).getImage());
holder.ItemName.setText(menuItemsModel.get(position).getItemName());
holder.ItemCost.setText(menuItemsModel.get(position).getItemCost());
//Picasso.with(context).load(menuItemsModel.get(position).getImage()).into(holder.imageView);
}
#Override
public int getItemCount() {
return menuItemsModel.size();
}
public class RecyclerViewHolder extends RecyclerView.ViewHolder implements
View.OnClickListener {
public ImageView imageView;
public TextView ItemName, ItemCost;
Context ctx;
List<MenuItemsModel> menuItemsModels;
public RecyclerViewHolder(View view, Context ctx, List<MenuItemsModel> menuItemsModels) {
super(view);
this.ctx = ctx;
this.menuItemsModels = menuItemsModels;
view.setOnClickListener(this);
imageView = view.findViewById(R.id.biriyani_menu_item);
ItemName = view.findViewById(R.id.item_name);
ItemCost = view.findViewById(R.id.item_cost);
}
#Override
public void onClick(View v) {
int position = getAdapterPosition();
MenuItemsModel model = this.menuItemsModels.get(position);
Intent i = new Intent(this.ctx, CategoryDescription.class);
i.putExtra("ImageId", model.getImage());
i.putExtra("ItemName", model.getItemName());
i.putExtra("ItemCost", model.getItemCost());
this.ctx.startActivity(i);
}
}
}
** Here is my MainActivity class **
public class BiryanisActivity extends AppCompatActivity implements
View.OnClickListener, NetworkOperationListener{
RecyclerView recyclerView;
MenusRecyclearView menusRecyclearView;
RecyclerView.LayoutManager layoutManager;
List<MenuItemsModel> menuItemsModel;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.biriyanis_activity);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
menuItemsModel = new ArrayList<>();
recyclerView = (RecyclerView) findViewById(R.id.recyclearview_menu);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
recyclerView.setItemAnimator(new DefaultItemAnimator());
menusRecyclearView = new MenusRecyclearView(this, menuItemsModel);
recyclerView.setAdapter(menusRecyclearView);
HttpAdapter.getMenuItemsList(this,"MenuItemsList");
//prepareData();
}
/* public void prepareData() {
MenuItemsModel data = new MenuItemsModel(R.drawable.item5, "Chicken Dhum
Biriyani", "Rs.240");
menuItemsModel.add(data);
MenuItemsModel data1 = new MenuItemsModel(R.drawable.item2, "Chicken
Chilli Biriyani", "Rs.260");
menuItemsModel.add(data1);
MenuItemsModel data2 = new MenuItemsModel(R.drawable.item3, "Chicken
Tandhuri Biriyani", "Rs.280");
menuItemsModel.add(data2);
MenuItemsModel data3 = new MenuItemsModel(R.drawable.item4, "Chicken
Moghulai Biriyani", "Rs.230");
menuItemsModel.add(data3);
MenuItemsModel data4 = new MenuItemsModel(R.drawable.item1, "Chicken
Special Biriyani", "Rs.220");
menuItemsModel.add(data4);
MenuItemsModel data5 = new MenuItemsModel(R.drawable.item1, "Chicken
Mandi Biriyani", "Rs.210");
menuItemsModel.add(data5);
}*/
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
onBackPressed();
return true;
}
return false;
}
#Override
public void onClick(View view) {
}
#Override
public void operationCompleted(NetworkResponse response) {
if (response.getStatusCode() == 200) {
if (response.getTag().equals("MenuItemsList")) {
try {
JSONObject jsonObjects = new JSONObject(response.getResponseString());
if (jsonObjects.getString("Data").equals("null")) {
Toast.makeText(this, "No Data Found", Toast.LENGTH_SHORT).show();
return;
}
JSONArray jsonArray = jsonObjects.getJSONArray("Data");
for (int j=0; j<jsonArray.length(); j++) {
JSONObject jsonObject = jsonArray.getJSONObject(j);
MenuItemsModel data = new Gson().fromJson(jsonObject.toString(),MenuItemsModel.class);
//Picasso.with(this).load(data.getImage()).into();
Picasso.with(this).load(data.getImage()).into(holder.imageView);
/* int image = data.getImage();
String name = data.getItemName();
String cost = data.getItemCost();
//picaso(image, imageView);*/
menuItemsModel.add(data);
}
MenusRecyclearView menusRecyclearView = new MenusRecyclearView(this,menuItemsModel);
recyclerView.setAdapter(menusRecyclearView);
} catch (JSONException e) {
e.printStackTrace();
}
}
} else {
Toast.makeText(this, "Failed to Connect Server, Please try again later", Toast.LENGTH_SHORT).show();
}
}
public void picaso(String path, ImageView imageView) {
if (!path.equals("")) {
Picasso.with(this).load(path).into(imageView);
}
}
}
Well, you are on the right track. You need to uncomment this line:
//Picasso.with(context).load(menuItemsModel.get(position).getImage()).into(holder.imageView);
And, the .getImage() needs to become your URL. That means, you should store the image url inside MenuItemsModel. Now your image is an int, and should be of a type of String so you can pass the URL to it.
Also see this answer here:
https://stackoverflow.com/a/41157030/5457878
In my application I want use two recyclerView into one Activity.
I want when click on items of one of this recylerView's items , add item to another recyclerView.
I write below codes, when click on items just add lasted item info to another recyclerView.
But I want when click on each items, add this each items into another recyclerView not just add lasted items.
Now just add lasted items, but I want click each item add this item.
My Activity code:
public class SuggestFilmActivity extends AppCompatActivity implements SuggestedListener {
#BindView(R.id.toolbarTitleTxt)
TextView toolbarTitleTxt;
#BindView(R.id.suggestFilm_searchEditText)
EditText suggestFilm_searchEditText;
#BindView(R.id.suggestFilm_searchBtn)
ImageView suggestFilm_searchBtn;
#BindView(R.id.suggestFilm_recyclerView)
RecyclerView suggestFilm_recyclerView;
#BindView(R.id.suggestFilm_recyclerViewProgress)
ProgressBar suggestFilm_recyclerViewProgress;
#BindView(R.id.newsPageLoadLay)
RelativeLayout newsPageLoadLay;
#BindView(R.id.suggestFilm_recyclerViewSendUser)
RecyclerView suggestFilm_recyclerViewSendUser;
private Context context;
private SuggestFilmAdapter suggestFilmAdapter;
private SuggestFilmUserAdapter suggestFilmUserAdapter;
private List<Result> model = new ArrayList<>();
private InterfaceApi api;
private SharedPrefrencesHandler prefrencesHandler;
private String token;
private GridLayoutManager gridLayoutManager;
private LinearLayoutManager linearLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_suggest_film);
//Initialize
ButterKnife.bind(this);
context = this;
prefrencesHandler = new SharedPrefrencesHandler(context);
api = ApiClient.getClient().create(InterfaceApi.class);
suggestFilmAdapter = new SuggestFilmAdapter(context, model, this);
gridLayoutManager = new GridLayoutManager(context, 3);
linearLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
//Get token
token = prefrencesHandler.getFromShared(SharedPrefrencesKeys.TOKEN.name());
//Set toolbar title
toolbarTitleTxt.setText(context.getResources().getString(R.string.SuggestToFollowers));
//Init followers recyclerView
suggestFilm_recyclerView.setLayoutManager(gridLayoutManager);
suggestFilm_recyclerView.setHasFixedSize(true);
//Init send user recyclerView
suggestFilm_recyclerViewSendUser.setLayoutManager(linearLayoutManager);
suggestFilm_recyclerViewSendUser.setHasFixedSize(true);
//Load more
newsPageLoadLay.setVisibility(View.GONE);
suggestFilm_recyclerView.setOnScrollListener(new EndlessRecyclerGridPage1(gridLayoutManager) {
#Override
public void onLoadMore(int current_page) {
newsPageLoadLay.setVisibility(View.VISIBLE);
Call<SeriesWhoWatchedResponse> call = api.getSuggestFilmUsers(token, filmSendData(current_page));
call.enqueue(new Callback<SeriesWhoWatchedResponse>() {
#Override
public void onResponse(Call<SeriesWhoWatchedResponse> call, Response<SeriesWhoWatchedResponse> response) {
if (response.body().getData() != null && response.body().getStatusCode() != 401
&& response.body().getStatusCode() != 402) {
if (response.body().getData().getResult().size() > 0) {
suggestFilmAdapter.addNewItem(response.body().getData().getResult());
//Gone no explore
newsPageLoadLay.setVisibility(View.GONE);
}
} else {
prefrencesHandler.remove(SharedPrefrencesKeys.TOKEN.name());
startActivity(new Intent(context, LoginActivity.class));
}
newsPageLoadLay.setVisibility(View.GONE);
}
#Override
public void onFailure(Call<SeriesWhoWatchedResponse> call, Throwable t) {
newsPageLoadLay.setVisibility(View.GONE);
}
});
}
});
//Get user data
getUserData();
}
private void getUserData() {
suggestFilm_recyclerViewProgress.setVisibility(View.VISIBLE);
Call<SeriesWhoWatchedResponse> call = api.getSuggestFilmUsers(token, filmSendData(1));
call.enqueue(new Callback<SeriesWhoWatchedResponse>() {
#Override
public void onResponse(Call<SeriesWhoWatchedResponse> call, Response<SeriesWhoWatchedResponse> response) {
if (response.body().getData() != null && response.body().getData().getResult().size() > 0
&& response.body().getStatusCode() != 401 && response.body().getStatusCode() != 402) {
model.clear();
model.addAll(response.body().getData().getResult());
suggestFilmAdapter.notifyDataSetChanged();
suggestFilm_recyclerView.setAdapter(suggestFilmAdapter);
} else {
prefrencesHandler.remove(SharedPrefrencesKeys.TOKEN.name());
startActivity(new Intent(context, LoginActivity.class));
}
suggestFilm_recyclerViewProgress.setVisibility(View.GONE);
}
#Override
public void onFailure(Call<SeriesWhoWatchedResponse> call, Throwable t) {
suggestFilm_recyclerViewProgress.setVisibility(View.GONE);
}
});
}
private SuggestFilmSendData filmSendData(int page) {
SuggestFilmSendData sendData = new SuggestFilmSendData();
sendData.setKeyword("");
sendData.setPageIndex(page);
sendData.setPageSize(10);
return sendData;
}
private ArrayList<SuggestFilmAddUser> prepareData(int id, String name, String image) {
ArrayList<SuggestFilmAddUser> suggestFilmAddUserList = new ArrayList<>();
SuggestFilmAddUser suggestFilmAddUser = new SuggestFilmAddUser();
suggestFilmAddUser.setId(id);
suggestFilmAddUser.setName(name);
suggestFilmAddUser.setImage(image);
suggestFilmAddUserList.add(suggestFilmAddUser);
return suggestFilmAddUserList;
}
#Override
public void onSend(int Id, String name, String image) {
ArrayList<SuggestFilmAddUser> suggestFilmAddUserList = prepareData(Id, name, image);
suggestFilmUserAdapter = new SuggestFilmUserAdapter(context, suggestFilmAddUserList);
suggestFilm_recyclerViewSendUser.setAdapter(suggestFilmUserAdapter);
}
}
One recyclerView adapter and send data Interface codes:
public class SuggestFilmAdapter extends RecyclerView.Adapter<SuggestFilmAdapter.ViewHolder> {
private Context context;
private List<Result> model;
private SuggestedListener suggestedListener;
public SuggestFilmAdapter(Context context, List<Result> model, SuggestedListener suggestedListener) {
this.context = context;
this.model = model;
this.suggestedListener = suggestedListener;
}
#Override
public SuggestFilmAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.row_suggest_film_users_followers, parent, false);
return new SuggestFilmAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(final SuggestFilmAdapter.ViewHolder holder, final int position) {
//Name
holder.row_suggestFilmProfileName.setText(model.get(position).getName());
//Image
Glide.with(context)
.load(model.get(position).getImageUrl())
.asBitmap()
.placeholder(R.drawable.default_image)
.diskCacheStrategy(DiskCacheStrategy.SOURCE)
.override(300, 300)
.into(new BitmapImageViewTarget(holder.row_suggestFilmProfileImage) {
#Override
protected void setResource(Bitmap resource) {
if (context == null) return;
RoundedBitmapDrawable circularBitmapDrawable =
RoundedBitmapDrawableFactory.create(context.getResources(), resource);
circularBitmapDrawable.setCircular(true);
holder.row_suggestFilmProfileImage.setImageDrawable(circularBitmapDrawable);
}
});
//Is Mutual
if (model.get(position).getIsMutual()) {
holder.row_suggestFilmIsOk.setVisibility(View.VISIBLE);
} else {
holder.row_suggestFilmIsOk.setVisibility(View.GONE);
}
holder.row_suggestedLay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
suggestedListener.onSend(model.get(position).getUserId(),
model.get(position).getName(),
model.get(position).getImageUrl());
}
});
}
#Override
public int getItemCount() {
return model.size();
}
public void addNewItem(List<Result> newContent) {
int start = this.model.size();
int end = newContent.size();
model.addAll(newContent);
notifyDataSetChanged();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private ImageView row_suggestFilmProfileImage, row_suggestFilmIsOk;
private TextView row_suggestFilmProfileName;
private RelativeLayout row_suggestedLay;
public ViewHolder(View itemView) {
super(itemView);
row_suggestFilmProfileImage = (ImageView) itemView.findViewById(R.id.row_suggestFilmProfileImage);
row_suggestFilmIsOk = (ImageView) itemView.findViewById(R.id.row_suggestFilmIsOk);
row_suggestFilmProfileName = (TextView) itemView.findViewById(R.id.row_suggestFilmProfileName);
row_suggestedLay = (RelativeLayout) itemView.findViewById(R.id.row_suggestedLay);
}
}
}
Model class :
public class SuggestFilmAddUser {
private int id;
private String name;
private String image;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
}
How can I it? Please help me
Inside onSend() , you need to add each objects to an arraylist which should be declared globally. Then call notifyItemInserted(arraylist.size()-1) in adapter to refresh recyclerview
public class SuggestFilmActivity ....
{ ArrayList<SuggestFilmAddUser> suggestFilmAddUserList=new ArrayList();
SuggestFilmUserAdapter suggestFilmUserAdapter;
......
......
protected void onCreate(Bundle savedInstance)
{....
....
....
suggestFilmUserAdapter = new SuggestFilmUserAdapter(context,
suggestFilmAddUserList);
suggestFilm_recyclerViewSendUser.setAdapter(suggestFilmUserAdapter);
.....
.....
}
public void onSend(int Id, String name, String image) {
SuggestFilmAddUser suggestFilmAddUser = new SuggestFilmAddUser();
suggestFilmAddUser.setId(id);
suggestFilmAddUser.setName(name);
suggestFilmAddUser.setImage(image);
suggestFilmAddUserList.add(suggestFilmAddUser);
suggestFilmUserAdapter.notifyItemInserted(suggestFilmAddUserList.size()-1)
}
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: