I am using a Recyclerview and want to add images in it which works fine. I want to use int array of drawables in my resource folder and load images from a set folder on my sdcard. I have a string array which lists paths of all images and sets a textview in my cardview but i can't convert that into an int array to load the images.
Here is my code, i have commented out the string array and int arrays that load the drawable.resources and textviews which are hardcoded.
If you need any more info/code then i can post it. Thanks in advance.
The feed.setMyFiles(previewsPath [i]); works fine.
The feed.setThumbnail(intarray[i]); is where im stuck.
MainActivity
public class MainCardActivity extends ActionBarActivity {
private RecyclerView recyclerView;
private CardView cardView;
private ArrayList<FeedProperties> os_versions;
private RecyclerView.Adapter mAdapter;
// private RecyclerView.LayoutManager mLayoutManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.maincardlayout);
initContrls();
}
private void initContrls() {
//cardView = (CardView) findViewById(R.id.cardList);
recyclerView = (RecyclerView) findViewById(R.id.my_recycler_view);
// final String[] versions = {"Synergy", "Synergy", "Synergy", "Synergy", "Synergy", "Synergy", "Synergy"};
// final int[] previewsImages = {R.drawable.psss, R.drawable.psss, R.drawable.psss, R.drawable.psss, R.drawable.sss, R.drawable.dog, R.drawable.sss, R.drawable.psss, R.drawable.dog, R.drawable.dog, R.drawable.sss, R.drawable.psss};
// Check for count
os_versions = new ArrayList<FeedProperties>();
File pathToFiles = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/Overlays/Previews");
String[] previewsPath = pathToFiles.list();
//ArrayList<String> filePaths;
//populate filePaths with your list of file paths.
//feed.setThumbnail(Drawable.createFromPath(filePaths.get(i)));
//int intarray[] = new int[previewsPath.length];
// for (int i = 0; i < previewsPath.length; i++) {
// FeedProperties feed = new FeedProperties();
ArrayList<String> filePaths = new ArrayList<>();
for (String s : pathToFiles.list()) {
filePaths.add(s); }
for (int i = 0; i < previewsPath.length; i++) {
FeedProperties feed = new FeedProperties();
feed.setThumbnail(Drawable.createFromPath(filePaths.get(i)));
feed.setMyFiles(previewsPath [i]);
//feed.setMyFiles(previewsPath [i]);
// intarray[i] = Integer.parseInt(previewsPath[i]);
// feed.setThumbnail(intarray[i]);
os_versions.add(feed);
}
recyclerView.setHasFixedSize(true);
// ListView
recyclerView.setLayoutManager(new LinearLayoutManager(this));
//Grid View
// recyclerView.setLayoutManager(new GridLayoutManager(this,2,1,false));
//StaggeredGridView
// recyclerView.setLayoutManager(new StaggeredGridLayoutManager(2,1));
mAdapter = new CardViewDataAdapter(os_versions);
recyclerView.setAdapter(mAdapter);
}
}
Model class
public class FeedProperties {
private String title;
private String myfiles;
private int thumbnail;
public String getTitle() {
return title;
}
public String getMyFiles() {
return myfiles;
}
public void setMyFiles(String myfiles) {
this.myfiles = myfiles;
}
public void setTitle(String title) {
this.title = title;
}
public int getThumbnail() {
return thumbnail;
}
public void setThumbnail(int thumbnail) {
this.thumbnail = thumbnail;
}
}
Adapter Class
public class CardViewDataAdapter extends RecyclerView.Adapter<CardViewDataAdapter.ViewHolder> {
private static ArrayList<FeedProperties> dataSet;
public CardViewDataAdapter(ArrayList<FeedProperties> os_versions) {
dataSet = os_versions;
}
#Override
public CardViewDataAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
//create a new view
View itemLayoutView = LayoutInflater.from(viewGroup.getContext()).inflate(
R.layout.card_view, null);
//create ViewHolder
ViewHolder viewHolder = new ViewHolder(itemLayoutView);
return viewHolder;
}
#Override
public void onBindViewHolder(CardViewDataAdapter.ViewHolder viewHolder, int i) {
FeedProperties fp = dataSet.get(i);
viewHolder.tvVersionName.setText(fp.getTitle());
viewHolder.tvmyfilesName.setText(fp.getMyFiles());
viewHolder.iconView.setImageResource(fp.getThumbnail());
viewHolder.feed = fp;
}
#Override
public int getItemCount() {
return dataSet.size();
}
#Override
public long getItemId(int position) {
return position;
}
// inner class to hold a reference to each item of RecyclerView
public static class ViewHolder extends RecyclerView.ViewHolder {
public TextView tvVersionName;
public TextView tvmyfilesName;
public ImageView iconView;
public FeedProperties feed;
public ViewHolder(View itemLayoutView) {
super(itemLayoutView);
tvVersionName = (TextView) itemLayoutView.findViewById(R.id.tvVersionName);
tvmyfilesName = (TextView) itemLayoutView.findViewById(R.id.tvmyfilesName);
iconView = (ImageView) itemLayoutView.findViewById(R.id.iconId);
itemLayoutView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), SecondPage.class);
v.getContext().startActivity(intent);
Toast.makeText(v.getContext(), "os version is: " + feed.getTitle(), Toast.LENGTH_SHORT).show();
}
});
}
}
}
ArrayList<String> filePaths = new ArrayList<>();
for (String s : pathToFiles.list()) {
filePaths.add(s);
}
for (int i = 0; i < previewsPath.length; i++) {
FeedProperties feed = new FeedProperties();
feed.setThumbnail(Drawable.createFromPath(filePaths.get(i)));
feed.setMyFiles(previewsPath [i]);
//feed.setMyFiles(previewsPath [i]);
//intarray[i] = Integer.parseInt(previewsPath[i]);
//feed.setThumbnail(intarray[i]);
os_versions.add(feed);
}
have you tried using the picasso library? here's a tutorial http://www.101apps.co.za/index.php/articles/using-bitmaps-efficiently.html. There's also a link in this tutorial showing how to use picasso and recyclerview. And here's a link to Picasso's web page http://square.github.io/picasso/. Good luck
Related
I would like to update panel wise items in inner adapter item android recyclerview. When we pass the data dynamically.Data displaying is working fine. When we go to update the inner adapter item, it's not getting updated. But last item was getting update fine.
Activity.
public class PannelCreation extends AppCompatActivity {
RecyclerView userPanelRecycler;
List<String> roomPanels = new ArrayList<>();
List<JSONObject> roomItemObject = new ArrayList<JSONObject>();
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pannel_creation);
userPanelRecycler = findViewById(R.id.user_panel_recycler);
for(int i=0; i<=5;i++){
roomPanels.add("Panels "+i)
}
PanelAdapter panelAdapter = new PanelAdapter(getApplicationContext(),roomPanels);
userPanelRecycler.setLayoutManager(new LinearLayoutManager(this));
userPanelRecycler.setHasFixedSize(true);
userPanelRecycler.setAdapter(panelAdapter);
}
}
// OuterAdapter
class PanelAdapter extends RecyclerView.Adapter<PanelAdapter.ViewHolder>{
Context context;
List<String> roomPanelList;
RecyclerView.RecycledViewPool recycledViewPool;
List<ItemData> itemDataList = new ArrayList<>();
public PanelAdapter(Context context, List<String> roomPanels) {
this.context = context;
this.roomPanelList = roomPanels;
recycledViewPool = new RecyclerView.RecycledViewPool();
}
#NonNull
#Override
public PanelAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.panel_wise_layout,parent,false);
ViewHolder viewHolder = new ViewHolder(view);
viewHolder.itemsRecycler.setRecycledViewPool(recycledViewPool);
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull PanelAdapter.ViewHolder holder, int position) {
holder.userPanelName.setText(roomPanelList.get(position));
String cur_panelName = roomPanelList.get(position);
itemsAdapter = new ItemsAdapter(context);
holder.itemsRecycler.setLayoutManager(new GridLayoutManager(context,3));
holder. itemsRecycler.setHasFixedSize(true);
holder.itemsRecycler.setAdapter(itemsAdapter);
holder.itemsRecycler.setNestedScrollingEnabled(false);
try {
roomItemObject.clear();
JSONArray metaArray = new JSONArray(metaData);
int count = 0;
for(int i = 0;i<metaArray.length();i++){
JSONObject object = metaArray.getJSONObject(i);
String name = object.getString("name");
String[] rNum = name.split("_");
if(rNum[0].equalsIgnoreCase(roomNumber)){
roomItemObject.add(object);
}
count = count+1;
}
if(count == metaArray.length()){
int count1 = 0;
itemDataList.clear();
for(int i =0; i < roomItemObject.size();i++){
JSONObject itemObject1 = roomItemObject.get(i);
String groupNames = itemObject1.getString("groupNames");
String types = itemObject1.getString("type");
String metaValue = itemObject1.getString("metadata");
JSONObject panelObject = new JSONObject(metaValue);
String panel_name = panelObject.getString("panelName");
JSONObject valueObject = new JSONObject(panel_name);
String value = valueObject.getString("value");
if(value.equalsIgnoreCase(cur_panelName)){
String labels = itemObject1.getString("label");
String names = itemObject1.getString("name");
String state = itemObject1.getString("state");
String groupName = itemObject1.getString("groupNames");
String tags = itemObject1.getString("tags");
ItemData itemData = new ItemData();
itemData.setLabelName(labels);
itemData.setState(state);
itemData.setItemName(names);
itemData.setTags(tags);
itemData.setTypes(types);
itemData.setGroup(groupName);
itemDataList.add(itemData);
itemsAdapter.addItems(itemDataList);
itemsAdapter.notifyDataSetChanged();
}
}
}
}catch (JSONException e){
e.printStackTrace();
}
}
#Override
public int getItemCount() {
return roomPanelList.size();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return position;
}
public class ViewHolder extends RecyclerView.ViewHolder{
RecyclerView itemsRecycler;
TextView userPanelName;
Button deletePanel;
public ViewHolder(#NonNull View itemView) {
super(itemView);
itemsRecycler = itemView.findViewById(R.id.panel_item_recycler);
userPanelName = itemView.findViewById(R.id.test_panel_name);
deletePanel = itemView.findViewById(R.id.delete_panel);
}
}
}
//Inner Adapter
class ItemsAdapter extends RecyclerView.Adapter<ItemsAdapter.ItemHolder>{
Context mContext;
List<ItemData> innerItemDataList = new ArrayList<>();
List<JSONObject> itemObjectList = new ArrayList<JSONObject>();
List<JSONObject> recObjectList = new ArrayList<>();
ItemData itemData;
public ItemsAdapter(Context context) {
this.mContext = context;
this.itemData = new ItemData();
}
public void addItems(List<ItemData> itemData){
this.innerItemDataList.clear();
this.innerItemDataList.addAll(itemData);
notifyDataSetChanged();
}
#NonNull
#Override
public ItemsAdapter.ItemHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View itemView = LayoutInflater.from(mContext).inflate(R.layout.panel_wise_item,parent,false);
return new ItemHolder(itemView);
}
#Override
public void onBindViewHolder(#NonNull ItemHolder holder, int position) {
itemData = innerItemDataList.get(position);
if(itemData != null){
holder.itemNames.setText(itemData.getLabelName());
}
#Override
public int getItemCount() {
return innerItemDataList.size();
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public int getItemViewType(int position) {
return position;
}
public class ItemHolder extends RecyclerView.ViewHolder {
TextView itemNames;
LinearLayout itemLayout;
ImageView itemImg;
public ItemHolder(#NonNull View itemView) {
super(itemView);
itemNames = itemView.findViewById(R.id.panel_item_name);
itemLayout = itemView.findViewById(R.id.panel_light_linear);
itemImg = itemView.findViewById(R.id.panel_item_img);
}
}
public void updateItem(String itemName,String state){
for(int j=0;j<innerItemDataList.size();j++){
if(itemName.equalsIgnoreCase(innerItemDataList.get(j).getItemName())){
innerItemDataList.get(j).setState(state);
notifyDataSetChanged();
}
}
}
}
//Inner adapter data model class
public class ItemData {
String labelName;
String itemName;
String state;
String group;
String tags;
String types;
public String getTypes() {
return types;
}
public void setTypes(String types) {
this.types = types;
}
public String getTags() {
return tags;
}
public void setTags(String tags) {
this.tags = tags;
}
public String getLabelName() {
return labelName;
}
public void setLabelName(String labelName) {
this.labelName = labelName;
}
public String getItemName() {
return itemName;
}
public void setItemName(String itemName) {
this.itemName = itemName;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}
}
How to update specific item in inner adapter android nested recycler view.Can anyone guide me how to deal with update specific item. One more thing have observed inner adapter returns last position of array list only. Items are updating fine in last position of array list. When trying to updating the rest of position array list items, not getting updated.
Thanks in Advance.
Amar.
In outer adapter when ever data changes need to notify. Try this code
panelAdapter.notifyDataSetChanged();
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
I have a RecyclerView inside a Fragment within Activity. I need to refresh my RecyclerView from Activity. I added a method inside Fragment which called notifyDatasetChanged to refresh RecyclerView. But notifyDatasetChanged didn't work.
Here is my Fragment.
public class CategoryFragment extends Fragment{
private RecyclerView recyclerView;
private EventsAdapter adapter;
static Context context = null;
private List<Category> categories;
private List<Item> allItems = new ArrayList();
private ReminderDatabase dbHandler;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(!checkDatabase()){
copyDatabase();
}
context = getActivity();
dbHandler = new ReminderDatabase(context);
fillAllItems();
}
public void fillAllItems(){
categories = dbHandler.getAllCategory();
for(int i=0;i<categories.size();i++){
Category category = categories.get(i);
Item categoryItem = new Item(category.getTitle(),category.getColor(),Category.CATEGORY_TYPE);
allItems.add(categoryItem);
List<Event> events = dbHandler.getEventsByCategory(category.getTitle());
for(int j=0;j<events.size();j++){
Event e = events.get(j);
Item eventItem = new Item(e.getId(),e.getTitle(),e.getDescription(),e.getPlace(),e.getCategory(),e.getTime(),e.getDate(),categoryItem.getColor(),e.isShow(),Event.EVENT_TYPE);
allItems.add(eventItem);
}
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.category_fragment, container, false);
recyclerView = (RecyclerView) v.findViewById(R.id.recyclerView);
adapter = new EventsAdapter(getContext(),allItems);
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setAdapter(adapter);
return v;
}
public boolean checkDatabase(){
String path = "/data/data/com.example.materialdesign.reminder/databases/";
String filename = "Remind";
File file = new File(path+filename);
Log.d("Database","File exists -> "+file.exists());
return file.exists();
}
public void copyDatabase(){
String path = "/data/data/com.example.materialdesign.reminder/databases/Remind";
ReminderDatabase dbHandler = new ReminderDatabase(getContext());
dbHandler.getWritableDatabase();
InputStream fin;
OutputStream fout;
byte[] bytes = new byte[1024];
try {
fin = getActivity().getAssets().open("Remind");
fout = new FileOutputStream(path);
int length=0;
while((length = fin.read(bytes))>0){
fout.write(bytes,0,length);
}
fout.flush();
fout.close();
fin.close();
Log.d("Database","successfully copied database");
} catch (FileNotFoundException e) {
e.printStackTrace();
Log.d("Database","-Error" +e.getMessage());
} catch (IOException e) {
e.printStackTrace();
Log.d("Database","-Error" +e.getMessage());
}
}
#Override
public void onResume() {
super.onResume();
allItems.clear();
Log.d("TAG","onresume");
fillAllItems();
adapter.notifyDataSetChanged();
}
public void refresh(){
Log.d("c",allItems.size()+"");
allItems.clear();
fillAllItems();
Log.d("c",allItems.size()+"");
adapter.notifyDataSetChanged();
}
}
I called refresh method from MainActivity.
#Override
public void onInserted() {
fragment.refresh();
}
My Adapter is here.
public class EventsAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder>{
private Context context;
private List<Item> allItems = new ArrayList();
private HideOrShowListener hideOrShowListener;
public static final int EVENT_TYPE = 1;
public static final int CATEGORY_TYPE = 0;
private int lastPosition;
private boolean flag = false;
public EventsAdapter(Context context,List<Item> allItems){
this.context = context;
hideOrShowListener =(HideOrShowListener) context;
this.allItems = allItems;
}
#Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view;
switch (viewType){
case CATEGORY_TYPE:
view = LayoutInflater.from(context).inflate(R.layout.category_item,parent,false);
return new CategoryViewHolder(view);
case EVENT_TYPE:
view = LayoutInflater.from(context).inflate(R.layout.events_item,parent,false);
return new EventViewHolder(view);
}
return null;
}
#Override
public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
final Item item = allItems.get(position);
switch (item.getType()){
case CATEGORY_TYPE:
((CategoryViewHolder)holder).tvCategoryTitle.setText(item.getTitle());
((GradientDrawable)(((CategoryViewHolder)holder).categoryColorIcon).getBackground()).setColor(Color.parseColor(item.getColor()));
((CategoryViewHolder)holder).imgAddEvent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
hideOrShowListener.setHideOrShow(item,false);
}
});
break;
case EVENT_TYPE:
String[] time = item.getTime().trim().split(":");
int hour = Integer.parseInt(time[0]);
((EventViewHolder)holder).tvEventName.setText(item.getTitle());
((EventViewHolder)holder).tvTime.setText(hour<12?hour+" : "+time[1] +" am" : hour-12+" : "+time[1] +" pm" );
((EventViewHolder)holder).tvPlace.setText(item.getPlace());
if(item.getDescription().length()==0) {
item.setDescription("No Detail");
}
((EventViewHolder)holder).tvDescription.setText(item.getDescription());
if(item.isShow()){
((EventViewHolder)holder).descriptionLayout.animate().alpha(1).setDuration(200).setInterpolator(new AccelerateInterpolator()).start();
((EventViewHolder)holder).descriptionLayout.setVisibility(View.VISIBLE);
((EventViewHolder)holder).descriptionLayout.setSelected(true);
((EventViewHolder)holder).tvEdit.setVisibility(View.VISIBLE);
((EventViewHolder)holder).eventContainer.setSelected(true);
}else{
((EventViewHolder)holder).descriptionLayout.setVisibility(View.GONE);
((EventViewHolder)holder).descriptionLayout.animate().alpha(0).setDuration(500).start();
((EventViewHolder)holder).descriptionLayout.setSelected(false);
((EventViewHolder)holder).eventContainer.setSelected(false);
((EventViewHolder)holder).tvEdit.setVisibility(View.INVISIBLE);
}
((EventViewHolder)holder).tvEdit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
hideOrShowListener.setHideOrShow(item,true);
}
});
break;
}
}
#Override
public int getItemCount() {
Log.d("c",allItems.size()+"");
return allItems.size();
}
#Override
public int getItemViewType(int position) {
if(allItems!=null){
return allItems.get(position).getType();
}
return 0;
}
public class CategoryViewHolder extends RecyclerView.ViewHolder{
private TextView tvCategoryTitle;
private View categoryColorIcon;
private ImageView imgAddEvent;
public CategoryViewHolder(View itemView) {
super(itemView);
tvCategoryTitle = (TextView) itemView.findViewById(R.id.tvCategoryTitle);
categoryColorIcon = itemView.findViewById(R.id.categoryColorIcon);
imgAddEvent = (ImageView) itemView.findViewById(R.id.addEvent);
}
}
public class EventViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private LinearLayout descriptionLayout;
private RelativeLayout eventContainer;
private TextView tvEventName,tvTime,tvPlace,tvDescription,tvEdit;
public EventViewHolder(View itemView) {
super(itemView);
descriptionLayout = (LinearLayout) itemView.findViewById(R.id.descriptionLayout);
eventContainer = (RelativeLayout) itemView.findViewById(R.id.eventContainer);
tvEventName = (TextView) itemView.findViewById(R.id.tvEventName);
tvTime = (TextView) itemView.findViewById(R.id.tvTime);
tvPlace = (TextView) itemView.findViewById(R.id.tvPlace);
tvDescription = (TextView) itemView.findViewById(R.id.tvDescription);
tvEdit = (TextView) itemView.findViewById(R.id.tvEdit);
eventContainer.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(flag){
allItems.get(lastPosition).setShow(false);
}
allItems.get(getAdapterPosition()).setShow(true);
flag = true;
lastPosition = getAdapterPosition();
notifyDataSetChanged();
}
}
public interface HideOrShowListener{
public void setHideOrShow(Item item , boolean isEdit);
}
}
But when I click home button and reenter my application, my RecyclerView refresh. It means that notifyDatasetChanged in onResume method works. But in my refresh method, it doesn't work. How can I do this?
Are you sure this method is being called :
#Override
public void onInserted() {
fragment.refresh();
}
Make sure that you've a correct instance of the fragment. Or you can simply user interface with the refresh() method and implement it in the fragment.
hello i have this Json Data a link
and i parsing it like that
when i click into the image i want to parsing the JsonArray for the image to piccaso in recycler view like this ,
but i get all image like this picture
how i can solve this problem and get just the images for the item which i clicked ???
this is my module :
public class AppShowModule
{
private List<String> Allimage = new ArrayList<String>();
public List<String> getAllimage() {
return Allimage;}
public void setAllimage(List<String> allimage) {
Allimage = allimage;}
this is my Fragment
public class ImageListFragment extends Fragment {
List<AppShowModule> appShowModules;
List<AppShowModule> imagesModule;
RecyclerView AppRecyclerView;
RecyclerView.Adapter imageRecyclerViewadapter;
List<String> imageUrls;
String feedKey = "feed";
String entryKey = "entry";
String imageKey = "im:image";
String labelKey = "label";
String jsonUrl = "https://itunes.apple.com/jo/rss/topfreeapplications/limit=50/json";
RequestQueue requestQueue;
private RecyclerView.LayoutManager mLayoutManager;
public ImageListFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_image_list, container, false);
}
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
AppRecyclerView = (RecyclerView) getView().findViewById(R.id.imageRecyclerView);
imagesModule = new ArrayList<>();
appShowModules = new ArrayList<>();
imageUrls = new ArrayList<>();
JsonAppShowData();
}
public void JsonAppShowData() {
final JsonObjectRequest jsonObjectRequest = new JsonObjectRequest( jsonUrl, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray jsonArray = response.getJSONObject(feedKey).getJSONArray( entryKey );
AppShowModule appShowModule = new AppShowModule();
for (int i = 0; i < jsonArray.length(); i++) {
JSONArray imageArray = response.getJSONObject(feedKey).getJSONArray(entryKey).getJSONObject(i).getJSONArray(imageKey);
for (int j = 0; j < imageArray.length(); j++) {
String image = imageArray.getJSONObject(j).getString(labelKey).toString();
imageUrls.add(image);
appShowModule.setAllimage(imageUrls);
appShowModules.add(appShowModule);}}
imageRecyclerViewadapter = new ImageListAdapter(appShowModules,getContext(),imageUrls);
AppRecyclerView.setAdapter(imageRecyclerViewadapter);
} catch (JSONException e) {
e.printStackTrace();
}}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e( "LOG", error.toString() );
}
} );
requestQueue = Volley.newRequestQueue( getContext() );
requestQueue.add(jsonObjectRequest);
mLayoutManager = new GridLayoutManager( getContext().getApplicationContext(),3);
AppRecyclerView.setLayoutManager(mLayoutManager); }}
and this is the Recycler adapter
public class ImageListAdapter extends RecyclerView.Adapter<ImageListAdapter.ViewHolder> {
List<AppShowModule> appShowModules;
List<String> imageUrl;
Context context;
public ImageListAdapter(List<AppShowModule> appShowModules, Context context ,List<String>imageUrls
){
super();
this.imageUrl =imageUrls;
this.appShowModules = appShowModules;
this.context = context;}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from( parent.getContext() ).inflate( R.layout.imagelayout, parent,false );
ViewHolder viewHolder = new ViewHolder( v );
return viewHolder;}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Picasso.with(context).load(imageUrl.get(position)).into(holder.appImage);
}
public int getItemCount() {
return imageUrl.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
public ImageView appImage;
public ViewHolder(View itemView) {
super(itemView);
appImage = (ImageView) itemView.findViewById( R.id.appImage);
}}}
and this is the activity that have the image view where click
public class ListViewDetailsFragment extends Fragment {
ImageView AppImage;
TextView AppName,AppArtist,AppContentType,AppRights,AppCategory,AppRealseDate,AppSammary;
ImageButton AppLink;
Context context;
public ListViewDetailsFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_list_view_details, container, false);}
public void onActivityCreated(#Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
AppImage = (ImageView) getView().findViewById(R.id.imageView);
AppName = (TextView) getView().findViewById(R.id.textname);
AppArtist = (TextView) getView().findViewById(R.id.textartest);
AppContentType = (TextView) getView().findViewById(R.id.textcontent);
AppRights = (TextView) getView().findViewById(R.id.textrights);
AppCategory = (TextView) getView().findViewById(R.id.textCategory);
AppRealseDate = (TextView) getView().findViewById(R.id.textRelease);
AppSammary = (TextView) getView().findViewById(R.id.textSummary);
AppLink = (ImageButton) getView().findViewById(R.id.imageButton);
String name = getActivity().getIntent().getExtras().getString("App_name");
final String image = getActivity().getIntent().getExtras().getString("App_image");
String artist = getActivity().getIntent().getExtras().getString("App_artist");
String contentType = getActivity().getIntent().getExtras().getString("App_ContentType");
String rights = getActivity().getIntent().getExtras().getString("App_Rights");
String category = getActivity().getIntent().getExtras().getString("App_Category");
String realse = getActivity().getIntent().getExtras().getString("App_ReleaseDate");
final String link = getActivity().getIntent().getExtras().getString("App_link");
String sammary = getActivity().getIntent().getExtras().getString("App_summary");
AppName.setText(name);
AppArtist.setText(artist);
AppContentType.setText(contentType);
AppRights.setText(rights);
AppCategory.setText(category);
AppRealseDate.setText(realse);
AppSammary.setText(sammary);
Picasso.with(context).load(image).into(AppImage);
AppLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getActivity().getBaseContext(),
WebView.class);
intent.putExtra("App_link", link);
getActivity().startActivity(intent);}});
AppImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String id = (String) view.getTag();
Intent intent = new Intent(getActivity().getBaseContext(), ImageList.class);
intent.putExtra("id", id);
getActivity().startActivity(intent);
}});}}
The json data has links to three different sized images, it looks to me like you are requesting that all three images are fetched. If you don't want all three, just select the size you want (index 0, 1 or 2) and pull that image only.
JSONArray imageArray = response.getJSONObject(feedKey).getJSONArray(entryKey).getJSONObject(i).getJSONArray(imageKey);
for (int j = 0; j < imageArray.length(); j++) {
String image = imageArray.getJSONObject(j).getString(labelKey).toString();
imageUrls.add(image);
...
}
Sample Data:
"im:image":[
{
"label":"http://is1.mzstatic.com/image/thumb/Purple20/v4/87/35/82/87358231-ce91-3d14-b306-95888c23db3c/mzl.gdgtivnk.png/53x53bb-85.png",
"attributes":{
"height":"53"
}
},
{
"label":"http://is5.mzstatic.com/image/thumb/Purple20/v4/87/35/82/87358231-ce91-3d14-b306-95888c23db3c/mzl.gdgtivnk.png/75x75bb-85.png",
"attributes":{
"height":"75"
}
},
{
"label":"http://is3.mzstatic.com/image/thumb/Purple20/v4/87/35/82/87358231-ce91-3d14-b306-95888c23db3c/mzl.gdgtivnk.png/100x100bb-85.png",
"attributes":{
"height":"100"
}
}
Update 9/13/2016
Based on what I think you are after, I still think your problem is in your nested for loop in the jsonAppShowData() method. Though you do appear to pass some sort of ID extra in from the previous activity, I don't see you filtering on that item ID anywhere in the for loop. You need to restrict the outer for loop to only the item you wish to show.
For the image scaling issue, it may either be how your layout is setup or you can try some of the Picasso resize calls.
I have three images stored in a table class called: "events" and table column called: "image" on Parse.com
I used two queries 1 to handle the displaying of the images and one to get another table's information (Those are all Strings)
THE PROBLEM IS:
The query that i used to get all the images only displays one of the three images in the RecyclerView instead of all three.
How can i display all three images from Parse.com inside a RecyclerView?
MY MAIN ACTIVITY:
public class MainActivity extends Activity {
//Defining Variables
protected Toolbar toolbar;
protected NavigationView navigationView;
private DrawerLayout drawerLayout;
protected Button mButtonHeader;
protected TextView mDayOfTheWeek;
protected TextView mDate;
//protected Context context;
//private long pageId = 137317903012386L;
private RecyclerView mRecyclerView;
//New Variables
private CustomAdapter mAdapter;
//Weather variables
//private ImageView weatherIconImageView;
private TextView temperatureTextView;
private TextView conditionTextView;
private TextView locationTextView;
private ProgressDialog dialog;
private ProgressDialog progressDialog;
final List<Information> data = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//RecyclerView with Parse
mRecyclerView = (RecyclerView) findViewById(R.id.recycler_view_layout);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
mAdapter = new CustomAdapter(getApplicationContext(), data);
//The Query i used to get the three images
ParseQuery<ParseObject> queryImgs = new ParseQuery<ParseObject> ("events");
//queryImgs.orderByAscending("order");
//queryImgs.setLimit(10);
queryImgs.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(final List<ParseObject> objects, ParseException e) {
//for (ParseObject obj_food : objects) {
//if (obj_food.getInt("order") == order) {
for (int i = 0; i < objects.size(); i++) {
//final ParseFile file = obj_food.getParseFile("image");
//Information information = new Information();
//information.mEventsPhotoID = objects.get(i).getParseFile("image");
final ParseFile file = objects.get(i).getParseFile("image");
//bitmap
file.getDataInBackground(new GetDataCallback() {
public void done(byte[] data, ParseException e) {
if (e == null) {
Bitmap bmp = BitmapFactory
.decodeByteArray(
data, 0,
data.length);
// Get the ImageView from
// main.xml
mEventsPhotoID = (ParseImageView) findViewById(R.id.eventsPhotoID);
//mEventsPhotoIDTwo = (ParseImageView)findViewById(R.id.eventsPhotoID);
// Set the Bitmap into the
// ImageView
mEventsPhotoID.setImageBitmap(bmp);
//mEventsPhotoIDTwo.setImageBitmap(bmp);
}
}
});
//}
//order++;
}
mRecyclerView.setAdapter(mAdapter);
}
});
//Query to load String data into the card view/recycler view
ParseQuery<ParseObject> query = ParseQuery.getQuery("events");
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> objects, ParseException e) {
if (e == null) {
for (int i = 0; i < objects.size(); i++) {
Information information = new Information();
information.mNewstTitle = objects.get(i).getString("name");
information.mNewsStory = objects.get(i).getString("shortinfo");
//information.partyCost = parseObject.getString("partyName");
String url=objects.get(i).getParseFile("image").getUrl();
//information.mEventsPhotoID = objects.getParseFile("partyFlyerImage");
//information.mEventsPhotoID = objects.get(i).getParseFile("image");
//information.mNewsPhotoIcon = R.drawable.newsitem));
//Initialize ImageView
ParseImageView imageViewPicasso = (ParseImageView) findViewById(R.id.eventsPhotoID);
//Loading image from below url into imageView
Picasso.with(MainActivity.this)
.load(url)
.into(imageViewPicasso);
data.add(information);
}
} else {
// something went wrong
}
//adapter.notifyItemRangeInserted(startPosition, imageUrls.length);
mRecyclerView.setAdapter(mAdapter);
}
});
}//END onCreate
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
drawerLayout.openDrawer(GravityCompat.START);
return true;
}
return super.onOptionsItemSelected(item);
}
}//End Main Activity
MY ADAPTER CLASS:
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.MyViewHolder> {
//private List<String> imageUrls = new ArrayList<>();
List<Information> data = Collections.emptyList();
private LayoutInflater inflater;
private Context context;
/*public CustomAdapter (Context context,List<Information>data){
this.context=context;
inflater=LayoutInflater.from(context);
this.data= data;
}*/
public CustomAdapter (Context context,List<Information>data){
this.context=context;
inflater=LayoutInflater.from(context);
this.data= data;
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType){
View view= inflater.inflate(R.layout.cardview_upcomingshows, parent, false);
MyViewHolder holder = new MyViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(MyViewHolder holder, int position){
Information current= data.get(position);
//holder.mEventsPhotoID.setImageResource(current.mEventsPhotoID);
holder.mNewstTitle.setText(current.mNewstTitle);
holder.mNewsStory.setText(current.mNewsStory);
holder.mEventsPhotoID.setParseFile(current.mEventsPhotoID);
//holder.mEventsPhotoIDTwo.setParseFile(current.mEventsPhotoIDTwo);
}
#Override
public int getItemCount(){
return data.size();
}
class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
//ImageView mEventsPhotoID;
TextView mNewstTitle;
TextView mNewsStory;
ParseImageView mEventsPhotoID;
//ParseImageView mEventsPhotoIDTwo;
public MyViewHolder(View itemView) {
super(itemView);
//promoterImage = (ParseImageView) itemView.findViewById(R.id.promoterPicImage);
mEventsPhotoID = (ParseImageView) itemView.findViewById(R.id.eventsPhotoID);
//mEventsPhotoIDTwo = (ParseImageView) itemView.findViewById(R.id.eventsPhotoIDTwo);
mNewstTitle = (TextView) itemView.findViewById(R.id.newsTitle);
mNewsStory = (TextView) itemView.findViewById(R.id.newsStory);
mNewstTitle.setOnClickListener(this);
mNewsStory.setOnClickListener(this);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Toast.makeText(context, "Recycle Click" + getLayoutPosition(), Toast.LENGTH_SHORT).show();
if(getLayoutPosition()==0){
Intent intentEventsWebView = new Intent(itemView.getContext(), EventsWebViewActivity.class);
//intentIndependenceDay.putExtra("MyClass", myclass);
intentEventsWebView.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
itemView.getContext().startActivity(intentEventsWebView);
}
if(getLayoutPosition()==1){
Intent intentIndependenceDay = new Intent(itemView.getContext(), NextActivity.class);
//intentIndependenceDay.putExtra("MyClass", myclass);
intentIndependenceDay.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
itemView.getContext().startActivity(intentIndependenceDay);
}
if(getLayoutPosition()==2){
Intent intentShelleyMaxwellDance = new Intent(itemView.getContext(), OtherActivity.class);
//intentIndependenceDay.putExtra("MyClass", myclass);
intentShelleyMaxwellDance.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
itemView.getContext().startActivity(intentShelleyMaxwellDance);
}
}
}
}
MY DATA MODEL CLASS(CONTAINING DATA FOR THE RECYCLER VIEW):
public class Information {
String mNewstTitle;
String mNewsStory;
ParseFile mEventsPhotoID;
}
instead of reading the ParseFile yourself, try using the Url approach mentioned here:
Displaying ParseFile Containing Images Using Their Urls In A RecyclerView