I want to pass images in the asset/drawable folder through adapter and then show them in a new activity. I have tried making research for guidance but didn't get what i want. I want to pass images as i pass texts from string-array to new activity.
This is my Adapter
public class MyAdapter1 extends RecyclerView.Adapter<MyHolder1> implements Filterable {
Context mContext;
ArrayList<Model1> models1, filterList1; // this array list create a list of array which parameter define in our class
CustomFilter1 filter1;
public MyAdapter1(Context context, ArrayList<Model1> models) {
this.mContext = context;
this.models1 = models;
this.filterList1 = models;
}
#NonNull
#Override
public MyHolder1 onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.row1, null); //this line inflate our row
return new MyHolder1(view); //this will return our view to holder class
}
#Override
public void onBindViewHolder(#NonNull final MyHolder1 myHolder, int i) {
myHolder.mTitle.setText(models1.get(i).getTitle()); //here is position
myHolder.mDesc.setText(models1.get(i).getDesc());
myHolder.mImageView.setImageResource(models1.get(i).getIcon()); // here we used imge resource
myHolder.setItemCLickListener(new ItemClickListener1() {
#Override
public void onItemClickListener(View v, int position) {
String gTitle = models1.get(position).getTitle();
String gDesc = models1.get(position).getDesc();
BitmapDrawable bitmapDrawable = (BitmapDrawable)myHolder.mImageView.getDrawable();
Bitmap bitmap = bitmapDrawable.getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] bytes = stream.toByteArray();
//get our data with intent
Intent intent = new Intent(mContext, NewActivity2.class);
intent.putExtra("actionBarTitle1", models1.get(position).getTitle());
intent.putExtra("brandNewDesc1", models1.get(position).getBrandNewDesc());
intent.putExtra("soundfile", models1.get(position).getSoundfile());
intent.putExtra("iImage", bytes);
mContext.startActivity(intent);
return;
}
});
}
#Override
public int getItemCount() {
return models1.size();
}
#Override
public Filter getFilter() {
if (filter1 == null){
filter1 = new CustomFilter1(filterList1, this);
}
return filter1;
}
}
This is the Model Class
public class Model1 {
String title;
String desc;
int icon;
int soundfile;
String brandNewDesc;
//constructor
public Model1(String title, String desc, String description, int icon, int music) {
this.title = title;
this.desc = desc;
this.icon = icon;
this.soundfile = music;
this.brandNewDesc = description;
}
//getters
public String getTitle() {
return title;
}
public String getDesc() {
return desc;
}
public String getBrandNewDesc() {
return brandNewDesc;
}
public int getIcon() {
return icon;
}
public int getSoundfile() {
return soundfile;
}
}
This is my NewActivity2 where i want to show images
private static final String URL="file:///android_asset/html_files/chant2.pdf";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new2);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
//Keeps android screen on while reading through
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
ActionBar actionBar = getSupportActionBar();
ImageView imageView = (ImageView)findViewById(R.id.ImPage1);
imageView.setImageDrawable(getResources().getDrawable(R.drawable.c1_1));
//get data from previous activity when item of activity is clicked using intent
Intent intent = getIntent();
String mActionBarTitle = intent.getStringExtra("actionBarTitle");
//setctionBar Title
actionBar.setTitle(mActionBarTitle);
//ok we are done, lets run the project
The NewActivity2 XML
<ScrollView
android:id="#+id/scroller"
android:layout_width="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
android:layout_height="wrap_content">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/ImPage1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scaleType="fitXY"
android:src="#drawable/page1_1" />
<ImageView
android:id="#+id/ImPage2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/ImPage1"
android:scaleType="fitXY"
android:src="#drawable/page1_2" />
<ImageView
android:id="#+id/ImPage3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/ImPage2"
android:scaleType="fitXY"
android:src="#drawable/page1_3" />
<ImageView
android:id="#+id/ImPage4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/ImPage3"
android:scaleType="fitXY"
android:src="#drawable/page1_4" />
</RelativeLayout>
</ScrollView>
</RelativeLayout>
It all depends on how do you want to pass the array.
If you want pass the list of arrays when clicking on any of the adapter images you can write an onclicklistener for each item.
Code here.
If you want to pass in the form of a button click also use the same inside the button click listener.
Intent intent=new Intent(getApplicationContext(),NewActivity2 .class);
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("VAR1", models1);
intent.putExtras(bundle);
this.startActivity(intent);
And when you reach the Activity2 in the onCreate method Use the below code snippet
Bundle bundle = getIntent().getExtras();
ArrayList<Model1> arraylist = bundle.getParcelableArrayList("VAR1");
Now you will have all the list of Model1 objects. So you can load the images like you did in the adapter class.
You can also get a detailed explanation in this video : https://youtu.be/OMCctaE66b8
Hope that answered your question.
Related
I'm trying to upgrade my PopupMenu so it would come with icons and custom styles.
I have created a new layout for it
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:layout_width="wrap_content" android:layout_height="wrap_content"
xmlns:android="http://schemas.android.com/apk/res/android">
<RelativeLayout
android:id="#+id/layout_sharea"
android:background="#drawable/share"
android:paddingLeft="10.0dip"
android:paddingRight="10.0dip"
android:layout_width="wrap_content"
android:layout_height="50.0dip"
android:onClick="share">
<TextView
android:id="#+id/sharetexta"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/share"
android:drawableLeft="#drawable/share_button"
android:drawablePadding="10.0dip"
android:layout_centerVertical="true" />
</RelativeLayout>
<RelativeLayout
android:id="#+id/layout_shareb"
android:background="#drawable/share"
android:paddingLeft="10.0dip"
android:paddingRight="10.0dip"
android:layout_width="wrap_content"
android:layout_height="50.0dip"
android:layout_below="#+id/layout_sharea"
android:onClick="share">
<TextView
android:id="#+id/sharetextb"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/share"
android:drawableLeft="#drawable/share_button"
android:drawablePadding="10.0dip"
android:layout_centerVertical="true" />
</RelativeLayout>
</RelativeLayout>
I want the PopupMenu to be customized (to be this layout) like in this picture
A PopupMenu is meant for displaying Menus and there really isn't a good way of customizing the appearance of the menu items. If you want something more flexible, your answer is ListPopupWindow.
private static final String TITLE = "title";
private static final String ICON = "icon";
private List<HashMap<String, Object>> data = new ArrayList<HashMap<String, Object>>();
// Use this to add items to the list that the ListPopupWindow will use
private void addItem(String title, int iconResourceId) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put(TITLE, title);
map.put(ICON, iconResourceId);
data.add(map);
}
// Call this when you want to show the ListPopupWindow
private void showListMenu(View anchor) {
ListPopupWindow popupWindow = new ListPopupWindow(this);
ListAdapter adapter = new SimpleAdapter(
this,
data,
android.R.layout.activity_list_item, // You may want to use your own cool layout
new String[] {TITLE, ICON}, // These are just the keys that the data uses
new int[] {android.R.id.text1, android.R.id.icon}); // The view ids to map the data to
popupWindow.setAnchorView(anchor);
popupWindow.setAdapter(adapter);
popupWindow.setWidth(400); // note: don't use pixels, use a dimen resource
popupWindow.setOnItemClickListener(myListener); // the callback for when a list item is selected
popupWindow.show();
}
Here is my demo for custom ListPopupWindow by custom adapter
Model
public class ListPopupItem {
private String title;
private int imageRes;
public ListPopupItem(String title, int imageRes) {
this.title = title;
this.imageRes = imageRes;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public int getImageRes() {
return imageRes;
}
}
ListAdapter
public class ListPopupWindowAdapter extends BaseAdapter {
private List<ListPopupItem> items;
public ListPopupWindowAdapter(List<ListPopupItem> items) {
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public ListPopupItem getItem(int i) {
return items.get(i);
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_list_popup, null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.tvTitle.setText(getItem(position).getTitle());
holder.ivImage.setImageResource(getItem(position).getImageRes());
return convertView;
}
static class ViewHolder {
TextView tvTitle;
ImageView ivImage;
ViewHolder(View view) {
tvTitle = view.findViewById(R.id.text);
ivImage = view.findViewById(R.id.image);
}
}
}
item_list_popup.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<ImageView
android:id="#+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
tools:ignore="ContentDescription"
tools:src="#mipmap/ic_launcher"
/>
<TextView
android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
tools:text="Title"
/>
</LinearLayout>
Finally, show ListPopupWindow
(In this demo, I show MATCH_PARENT popup here, you can show a specific with for popup (eg: 100px, 200px,...)
If you set popup width = WRAP_CONTENT, popup width will equals ANCHOR width)
private void showListPopupWindow(View anchor) {
List<ListPopupItem> listPopupItems = new ArrayList<>();
listPopupItems.add(new ListPopupItem("Menu 1", R.mipmap.ic_launcher));
listPopupItems.add(new ListPopupItem("Menu 2", R.mipmap.ic_launcher));
listPopupItems.add(new ListPopupItem("Menu 3", R.mipmap.ic_launcher));
final ListPopupWindow listPopupWindow =
createListPopupWindow(anchor, ViewGroup.LayoutParams.MATCH_PARENT, listPopupItems);
listPopupWindow.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
listPopupWindow.dismiss();
Toast.makeText(MainActivity.this, "clicked at " + position, Toast.LENGTH_SHORT)
.show();
}
});
listPopupWindow.show();
}
private ListPopupWindow createListPopupWindow(View anchor, int width,
List<ListPopupItem> items) {
final ListPopupWindow popup = new ListPopupWindow(this);
ListAdapter adapter = new ListPopupWindowAdapter(items);
popup.setAnchorView(anchor);
popup.setWidth(width);
popup.setAdapter(adapter);
return popup;
}
Example using
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
showListPopupWindow(view);
}
});
DEMO
This is my adapter and I save my image string type in Responsemodel class.
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.myviewholder>
{
List<ResponseModel> data;
private final IOtobusSaatleriInterface iOtobusSaatleriInterface;
Context context;
public MyAdapter(List<ResponseModel> data, IOtobusSaatleriInterface iOtobusSaatleriInterface, Context context) {
this.data = data;
this.iOtobusSaatleriInterface = iOtobusSaatleriInterface;
this.context = context;
}
#NonNull
#Override
public myviewholder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.singlerowdesign,parent,false);
return new myviewholder(view,iOtobusSaatleriInterface);
}
#Override
public void onBindViewHolder(#NonNull myviewholder holder, int position) {
holder.t1.setText(data.get(position).getName());
holder.t2.setText(data.get(position).getDesig());
Glide.with(holder.t1.getContext())
.load("http://example.site/Gurpinar/images/" +data.get(position).getImage()).into(holder.img);
}
#Override
public int getItemCount() {
return null!=data?data.size():0;
}
class myviewholder extends RecyclerView.ViewHolder{
ImageView img;
TextView t1,t2;
public myviewholder(#NonNull View itemView, IOtobusSaatleriInterface iOtobusSaatleriInterface) {
super(itemView);
img = itemView.findViewById(R.id.img);
t1 = itemView.findViewById(R.id.t1);
t2 = itemView.findViewById(R.id.t2);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (iOtobusSaatleriInterface != null){
int position = getAdapterPosition();
if (position != RecyclerView.NO_POSITION);
iOtobusSaatleriInterface.onItemClick(position);
Intent intent = new Intent(context,deneme.class);
intent.putExtra("name",data.get(position).getName());
intent.putExtra("resim","http://example.site/Gurpinar/images/");
context.startActivity(intent);
}
}
});
}
}
}
and my new empty activity
public class deneme extends AppCompatActivity {
TextView textView;
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_deneme);
textView = findViewById(R.id.textView);
imageView = findViewById(R.id.imageView);
Intent intent = getIntent();
String name = intent.getStringExtra("name");
String goruntu = intent.getStringExtra("resim");
String.valueOf(Glide.with(imageView).load(goruntu));
textView.setText(name);
}
}
And my new empty activity
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".deneme">
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="#mipmap/ic_launcher" />
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5sp"
android:gravity="left"
android:text="TextView"
android:textColor="#494545"
android:textSize="25sp"
app:layout_constraintBottom_toTopOf="#+id/imageView" />
</LinearLayout>
My problem is I can access name data but image cannot be displayed.
How can I access the selected photo? I take the photos in mysql database and with the url recyclerview.
Perhaps you can pass the image as a Base64 in the Intent and create in the new Activity a Imagefile from this String.
Create as Base64 String:
How to get raw string of an image from Bitmap in android?
Create the Imagefile again from the String:
Create image file from raw string data
In my own effort, I used SharedPreference to create memory for my savings. But I don't know how to finish it up and make it workable. I have already gone far and have saved my data in string using CData. But my app users insisted I should put favorite list where they can save lists of songs of their choices. I made my app using ListView with Adapter and when clicked opens the full detail of the song list in a new activity. I'm trying to create a favorite where a user has the option to click on favorite icon and save a list of song in the favorite list. In that same favorite list the user needs an option to either keep or delete the item from the favorite list.
This below is what I have been able to do that yielded no positive result. I don't know what to do next.
SharedPreference
public class PreferenceUtils {
private static final PreferenceUtils ourInstance = new PreferenceUtils();
private static SharedPreferences sharedPreferences;
private static Context context;
private static String APP_DATA_NAME = "SONGS";
static PreferenceUtils getInstance() {
return ourInstance;
}
private PreferenceUtils() {
}
public static void initialize(Context c) {
sharedPreferences = c.getSharedPreferences(APP_DATA_NAME, Context.MODE_PRIVATE);
context = c;
}
public static String getPreference(String key, String defaultValue) {
if (sharedPreferences == null) return null;
return sharedPreferences.getString(key, defaultValue);
}
public static boolean getPreference(String key, boolean defaultValue) {
if (sharedPreferences == null) return false;
return sharedPreferences.getBoolean(key, defaultValue);
}
public static Set<String> getPreference(String key) {
if (sharedPreferences == null) return null;
return sharedPreferences.getStringSet(key,null);
}
public static void setPreference(String key, String value) {
if (sharedPreferences == null) return;
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(key, value);
editor.commit();
}
public static void setPreference(String key, boolean value) {
if (sharedPreferences == null) return;
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(key, value);
editor.commit();
}
public static void setPreference(String key, Set<String> value) {
if (sharedPreferences == null) return;
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putStringSet(key, value);
editor.apply();
}
}
Item_row
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
app:cardCornerRadius="7dp"
app:cardElevation="4dp"
android:background="#F4F4F7"
app:cardUseCompatPadding="true">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="16dp">
<ImageView
android:layout_width="40dp"
android:layout_height="40dp"
android:id="#+id/imageIv"
android:src="#drawable/cpu"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/titleTv"
android:text="Title"
android:textSize="17sp"
android:textColor="#000000"
android:fontFamily="sans-serif-condensed"
android:layout_toRightOf="#id/imageIv"
android:layout_toEndOf="#id/imageIv"
android:layout_marginLeft="10dp"
android:layout_marginStart="10dp" />
<TextView
android:id="#+id/descriptionTv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/titleTv"
android:layout_marginLeft="10dp"
android:layout_marginTop="5dp"
android:layout_toEndOf="#id/imageIv"
android:layout_toRightOf="#id/imageIv"
android:text="descriptionTv"
android:textColor="#DF014C"
android:textSize="11sp"
android:textStyle="italic" />
<ImageView
android:id="#+id/fav"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:padding="2dp"
android:src="#drawable/ic_star_outline"/>
</RelativeLayout>
</androidx.cardview.widget.CardView>
MyHolder
public class MyHolder1 extends RecyclerView.ViewHolder implements View.OnClickListener {
ImageView mImageView;
TextView mTitle, mDesc;
ItemClickListener1 itemCLickListener;
MyHolder1(#NonNull View itemView) {
super(itemView);
this.mImageView = itemView.findViewById(R.id.imageIv);
this.mTitle = itemView.findViewById(R.id.titleTv);
this.mDesc = itemView.findViewById(R.id.descriptionTv);
itemView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
this.itemCLickListener.onItemClickListener(v, getLayoutPosition());
}
public void setItemCLickListener(ItemClickListener1 ic){
this.itemCLickListener = ic;
}
}
MyAdapter1
public class MyAdapter1 extends RecyclerView.Adapter<MyHolder1> implements Filterable {
Context mContext;
ArrayList<Model1> models, filterList; // this array list create a list of array which parameter define in our class
CustomFilter1 filter;
public MyAdapter1(Context context, ArrayList<Model1> models) {
this.mContext = context;
this.models = models;
this.filterList = models;
}
#NonNull
#Override
public MyHolder1 onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.row1, null); //this line inflate our row
return new MyHolder1(view); //this will return our view to holder class
}
#Override
public void onBindViewHolder(#NonNull final MyHolder1 myHolder, int i) {
myHolder.mTitle.setText(models.get(i).getTitle()); //here is position
myHolder.mDesc.setText(models.get(i).getDesc());
myHolder.mImageView.setImageResource(models.get(i).getIcon()); // here we used imge resource
myHolder.setItemCLickListener(new ItemClickListener1() {
#Override
public void onItemClickListener(View v, int position) {
String gTitle = models.get(position).getTitle();
String gDesc = models.get(position).getDesc();
BitmapDrawable bitmapDrawable = (BitmapDrawable)myHolder.mImageView.getDrawable();
Bitmap bitmap = bitmapDrawable.getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] bytes = stream.toByteArray();
//get our data with intent
Intent intent = new Intent(mContext, NewActivity1.class);
intent.putExtra("actionBarTitle", models.get(position).getTitle());
intent.putExtra("brandNewDesc", models.get(position).getBrandNewDesc());
intent.putExtra("iImage", bytes);
mContext.startActivity(intent);
return;
}
});
}
#Override
public int getItemCount() {
return models.size();
}
#Override
public Filter getFilter() {
if (filter == null){
filter = new CustomFilter1(filterList, this);
}
return filter;
}
}
Modal Class
public class Model1 {
private String title, description, desc;
private int icon;
String brandNewDesc;
//constructor
public Model1(String title, String desc, String description, int icon) {
this.title = title;
this.desc = desc;
this.icon = icon;
this.brandNewDesc = description;
}
//getters
public String getTitle() {
return title;
}
public String getDesc() {
return desc;
}
public String getBrandNewDesc() {
return brandNewDesc;
}
public int getIcon() {
return icon;
}
}
Example of data saved in String.xml
<string-array name="array_titles_1">
Mothering Sunday Wishes For my Mom
<item>"<![CDATA[I love my trip on trip track one]]>"</item>
<item>"<![CDATA[Back to my lover track two]]>"</item>
</string-array>
<string-array name="array_lyrics_1">
<item>"<![CDATA[description of song genre and sources]]>"</item>
<item>"<![CDATA[description of song genre and sources]]>"</item>
</string-array>
<string-array name="newbrandDesc_1">
<item>"<![CDATA[The new song detals
1. verse one
2. verse two....]]>"</item>
<item>"<![CDATA[The second song details
1. verse one
2. verse two....]]>"</item>
</string-array>
I have a RecyclerView which has CardView as its list items. The CardView have only 2 TextView and one ImageView.
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="70dp"
android:layout_marginTop="2dp"
android:layout_marginBottom="2dp"
android:id="#+id/dcCardView">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:background="#drawable/detail_coast_cardview_bg">
<ImageView
android:id="#+id/dcImage"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_marginStart="8dp"
android:src="#drawable/radiation"
android:layout_gravity="center_vertical" />
<LinearLayout
android:layout_gravity="center_vertical"
android:layout_marginStart="16dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="#+id/dcName"
android:textColor="#fff"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="212"
android:textSize="18dp" />
<TextView
android:textColor="#fff"
android:id="#+id/dcValue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="renu asdasasd"
android:textSize="18dp" />
</LinearLayout>
</LinearLayout>
</android.support.v7.widget.CardView>
The class that goes in it is this
public class DetailedCoastRecyclerView {
//region fields
private String name;
private String value;
private int imageName;
//end region fields
//constructor
public DetailedCoastRecyclerView() {}
public DetailedCoastRecyclerView(String name, String value, int image) {
this.name = name;
this.value = value;
this.imageName = image;
}
public String getName() {
return name;
}
public String getValue() {
return value;
}
public int getImageName() {
return imageName;
}
}
And my CoastDetailsActivity2
public class CoastDetailsActivity2 extends AppCompatActivity {
private Context context;
private SharedPreferences sharedPreferences;
private SharedPreferences.Editor editor;
private int coastId;
private String jsonCoastDetailsString = "";
private RecyclerView recyclerView;
private DetailedCoastAdapter detailedCoastAdapter;
private ImageView btnBlueFlag;
private ImageView btnHandycapFriendly;
private ImageView btnFavorite;
private ImageView btnWaze;
private LinearLayout mainLayout;
private Beach mBeach;
private TextView tvBeachName;
private DetailedCoastWithForcast detailedCoastWithForcast;
private DetailedBeachMetadata detailedBeachMetadata;
private DetailedBeachHourlyForecast dbhfToday;
private List<DetailedCoastRecyclerView> detailedCoastRecyclerViewList = new ArrayList<>();
private Map<String, String> windBearing = new HashMap<>();
private Map<String, String> jellyType = new HashMap<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_coast_details2);
setPointer();
}
private void setPointer() {
this.context = this;
mainLayout = (LinearLayout) findViewById(R.id.mainLayout);
sharedPreferences = context.getSharedPreferences(sharedPreferencesName, MODE_PRIVATE);
editor = sharedPreferences.edit();
tvBeachName = (TextView) findViewById(R.id.tvBeachName);
//start the forecast activity
tvBeachName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, ForecastActivity.class);
intent.putExtra("coastId", coastId);
startActivity(intent);
}
});
AndroidNetworking.initialize(context);
//get the coastId
Bundle extras = getIntent().getExtras();
if (extras == null) {
//TODO add snackbar for error
} else {
coastId = extras.getInt("coastId");
}
getBeachDetails();
recyclerView = (RecyclerView) findViewById(R.id.dcRecyclerView);
detailedCoastAdapter = new DetailedCoastAdapter(detailedCoastRecyclerViewList, context);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setItemAnimator(new DefaultItemAnimator());
recyclerView.setAdapter(detailedCoastAdapter);
}
}
And the adapter
public class ForecastAdapter extends RecyclerView.Adapter<ForecastAdapter.myViewHolder> {
Context context;
private List<DetailedCoastRecyclerView> dbhf0;
public ForecastAdapter(Context context, List<DetailedCoastRecyclerView> dbhf0) {
this.context = context;
this.dbhf0 = dbhf0;
}
#Override
public myViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.detailed_coast_card, parent, false);
return new myViewHolder(view);
}
#Override
public void onBindViewHolder(myViewHolder holder, int position) {
DetailedCoastRecyclerView dcrv = dbhf0.get(position);
holder.tvName.setText(dcrv.getName());
holder.tvValue.setText(dcrv.getValue());
//holder.ivImage.setImageResource(dcrv.getImageName());
Glide.with(context).load(dcrv.getImageName()).into(holder.ivImage);
}
#Override
public int getItemCount() {
return dbhf0.size();
}
public class myViewHolder extends RecyclerView.ViewHolder {
ImageView ivImage;
TextView tvName;
TextView tvValue;
public myViewHolder(View itemView) {
super(itemView);
ivImage = (ImageView) itemView.findViewById(R.id.dcImage);
tvName = (TextView) itemView.findViewById(R.id.dcName);
tvValue = (TextView) itemView.findViewById(R.id.dcValue);
}
}
}
When I run it, the getBeachDetails() method gets all the info from the server, add it to an ArrayList and calls notifyDataSetChanged() on the adapter.
I know its working because I see the name and value for every card but the images which are stored locally are not displayed.
I use the same adapter inside a ViewPager with 3 fragments and there everything is ok.
Any ideas?
You provided code of ForecastAdapter, but actually you are using DetailedCoastAdapter. Make sure whether they are the same.
Check whether you have a valid url/resource in dcrv.getImageName()
I guess your image resolution is too high that android buffer cant handle and throws exception while rendering your image, so as I know you have to decrease your image quality when loading it on ImageView.
In Picasso this is done like this by calling resize(width,height) method.
Picasso.with(context)
.load(res)
.resize(width,height)
.placeholder(placeHolder)
.into(view);
I guess it is done in the same way with Glide.
I have a GridView of ImageViews, and while I am building the GUI I currently want to convert some stock drawables into bitmaps, and set the ImageViews to these. They currently just come out as blanks, but as far as I can tell the code is along the correct lines.
The GridView XML: (it expands as more elements are added)
<com.example.tristan.studentshare.ExpandingGridView
android:id="#+id/achievement_grid"
android:layout_below="#+id/profile_details"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:columnWidth="100dp"
android:gravity="center"
android:numColumns="auto_fit"
android:stretchMode="columnWidth"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:layout_marginTop="4dp">
</com.example.tristan.studentshare.ExpandingGridView>
The row_grid_achievements XML
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="5dp">
<ImageView
android:id="#+id/achievement_image"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginRight="10dp"
android:src="#drawable/ic_person_black_24dp"/>
<TextView
android:id="#+id/achievement_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:textSize="20sp"/>
</LinearLayout>
The Achievement being displayed in the GridView:
public class Achievement {
private String id;
private String name;
private String description;
private Integer progress;
private Bitmap icon;
public Achievement(String id, String name, String description, Integer progress, Bitmap icon) {
this.id = id;
this.name = name;
this.description = description;
this.progress = progress;
this.icon = icon;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getDescription() {
return description;
}
public Integer getProgress() {
return progress;
}
public Bitmap getIcon() {
return icon;
}
}
The GridView adapter override:
static class RecordHolder {
TextView txtTitle;
ImageView imageItem;
public RecordHolder(TextView txtTitle, ImageView imageItem) {
this.txtTitle = txtTitle;
this.imageItem = imageItem;
}
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
RecordHolder holder = null;
if (row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new RecordHolder(
(TextView)row.findViewById(R.id.achievement_text),
(ImageView)row.findViewById(R.id.achievement_image));
row.setTag(holder);
}
else holder = (RecordHolder)row.getTag();
Achievement achievement = data.get(position);
holder.txtTitle.setText(achievement.getName());
holder.imageItem.setImageBitmap(achievement.getIcon());
return row;
}
The implementation in the Activity:
ExpandingGridView gridView;
ArrayList<Achievement> gridArray = new ArrayList<Achievement>();
AchievementGridViewAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile);
//TODO:Actual Achievement details from server
Bitmap icon = BitmapFactory.decodeResource(this.getResources(), R.drawable.ic_person_black_24dp);
for(int i = 0; i < 5; i++)
{
gridArray.add(new Achievement("0", "Achv" + i, "test", 50, icon));
}
gridView = (ExpandingGridView) findViewById(R.id.achievement_grid);
adapter = new AchievementGridViewAdapter(this, R.layout.row_grid_achievements, gridArray);
gridView.setAdapter(adapter);
}
The visual result:
The grid items should have an icon above them similar to the "profile picture"
In the getView() method of your adapter change the below line
holder.imageItem.setImageBitmap(achievement.getIcon());
according to below
holder.imageItem.setBackgroundDrawable(achievement.getIcon());
I hope it works
Firstly, instead of using GridView, I used RecyclerView, with a GridLayoutManager (http://blog.sqisland.com/2014/12/recyclerview-grid-with-header.html)
To have the elements I wanted displayed in the grid, the RecyclerView uses an Adapter and inflates each grid element with a custom layout, in the following link they use a CardView as the layout root (http://www.androidhive.info/2016/05/android-working-with-card-view-and-recycler-view/)
To get a Drawable instance from Resources, I use the following code:
Drawable d1 = ResourceCompat.getDrawable(getResources(), R.drawable.picture, null);
//or , depending on where your Drawable is,
Drawable d2 = ResourceCompat.getDrawable(getResources(), R.mipmap.picture, null);
In the code where it actually comes to setting the ImageView to a particular Drawable, I used the code:
//Using the Resource ID
myImageView.setImageResource(myResourceID);
//Using a Drawable instance
myImageView.setImageDrawable(myDrawable);
Note that in the AndroidHive link above, whichever of the the above two lines of code would be used in the adapter class, in the Overrided method 'onBindViewHolder'