custom listview with images - java

Hello guys im new to android dev and im having an unknown error with my code,i finished the code but when i run it sends me back to "dataprovider". can anyone please help me?
My fragment.
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
public class Places_Fragment extends ListFragment {
ListView listView;
int[] images ={R.drawable.cake_1,R.drawable.cake_2,R.drawable.cake_3,R.drawable.cake_4,R.drawable.cake_5,R.drawable.cake_6};
String[] places;
PlaceAdapter adapter;
public static Places_Fragment newInstance() {
Places_Fragment fragment = new Places_Fragment();
return fragment;
}
public Places_Fragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_places_, container, false);
listView =(ListView)rootView .findViewById(R.id.listView);
places = getResources().getStringArray(R.array.places);
int i=0;
adapter = new PlaceAdapter(getActivity(),R.layout.row_layout);
listView.setAdapter(adapter);
for(String item: places)
{
PlaceDataProvider dataProvider = new PlaceDataProvider(images[i],places[i]);
adapter.add(dataProvider);
i++;
}
return rootView;
}
}
My custom Adapter.
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Bonfire-ADv on 4/23/2016.
*/
public class PlaceAdapter extends ArrayAdapter {
List list =new ArrayList();
public PlaceAdapter(Context context, int resource) {
super(context, resource);
}
static class DataHandler
{
ImageView images;
TextView Places;
}
#Override
public void add(Object object) {
super.add(object);
list.add(object);
}
#Override
public int getCount() {
return this.list.size();
}
#Override
public Object getItem(int position) {
return this.list.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row;
row = convertView;
DataHandler handler;
if (convertView== null)
{
LayoutInflater inflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate (R.layout.row_layout, parent, false);
handler = new DataHandler();
handler.images = (ImageView) row.findViewById(R.id.image_view);
handler.Places = (TextView) row.findViewById(R.id.place_title);
row.setTag(handler);
}
else
{
handler = (DataHandler) row.getTag();
}
PlaceDataProvider dataProvider;
dataProvider = (PlaceDataProvider) this.getItem(position);
handler.images.setImageResource(dataProvider.getImages());
handler.Places.setText(dataProvider.getPlaces());
return row;
}
}
My dataprovider.
package com.selfstudios.cakeplanet;
public class PlaceDataProvider {
private int images;
private String places;
public PlaceDataProvider(int images,String places)
{
this.setImages(images);
this.setPlaces(places);
}
public int getImages() {
return images;
}
public void setImages(int images) {
this.images = images;
}
public String getPlaces() {
return places;
}
public void setPlaces(String places) {
this.places = places;
}
}
my frag 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="match_parent"
tools:context="com.selfstudios.cakeplanet.Places_Fragment">
<!-- TODO: Update blank fragment layout -->
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listView"
android:layout_weight="1" />
</LinearLayout>
my row xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="80dp">
<ImageView
android:layout_width="100dp"
android:layout_height="75dp"
android:id="#+id/image_view"
android:layout_alignParentStart="true"
android:layout_alignParentLeft="true"
android:paddingStart="2dp"
android:paddingLeft="2dp"
android:paddingEnd="2dp"
android:src="#drawable/cake_1"
/>
<TextView
android:id="#+id/place_title"
android:layout_width="175dp"
android:layout_height="75dp"
android:text="place name"
android:gravity="center"
android:layout_alignParentTop="false"
android:layout_centerHorizontal="true"
/>
<View
android:layout_width="match_parent"
android:layout_height="2dp"
android:background="#color/colorPrimaryDark"
android:layout_alignBottom="#+id/image_view">
</View>
</RelativeLayout>

Try replacing
for(String item: places)
with the more traditional
for(int i; i < places.size(); i++

Related

Why won't my CardView appear in my fragment?

I am following this tutorial on how to create Swipe Views using a View Pager and am trying to convert it to work with fragments.
My issue is that the cards are not appearing when I select my fragment.
I think the issue lies in this line of code
adapter = new Adapter(models, getActivity());
(originally adapter = new Adapter(models, this); in the tutorial), but I could be wrong.
I am relatively new to android studio and this is my first time using fragments, any help would be greatly appreciated!
Here is my code:
fragment_cards.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:background="#android:color/background_light"
>
<androidx.viewpager.widget.ViewPager
android:id="#+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clipToPadding="false"
android:foregroundGravity="center"
android:overScrollMode="never"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0"></androidx.viewpager.widget.ViewPager>
<Button
android:id="#+id/button_shuffle"
android:text="SHUFFLE"
android:textColor="#fff"
android:background="#drawable/round"
android:paddingLeft="30dp"
android:paddingRight="30dp"
android:layout_marginBottom="60dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
app:layout_constraintBottom_toBottomOf="#+id/viewPager"
app:layout_constraintEnd_toEndOf="#+id/viewPager"
app:layout_constraintStart_toStartOf="#+id/viewPager">
</Button>
</androidx.constraintlayout.widget.ConstraintLayout>
item.xml
<?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"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorPrimary">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:cardCornerRadius="20dp"
android:layout_margin="8dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="300dp">
<ImageView
android:id="#+id/image"
android:src="#drawable/brochure"
android:scaleType="centerCrop"
android:layout_width="match_parent"
android:layout_height="200dp"/>
<TextView
android:id="#+id/title"
android:textColor="#262626"
android:layout_below="#id/image"
android:layout_marginTop="10dp"
android:layout_marginLeft="16dp"
android:text="Brochure"
android:textSize="16sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<TextView
android:id="#+id/desc"
android:layout_below="#id/title"
android:layout_marginTop="3dp"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:maxLines="3"
android:drawablePadding="10dp"
android:ellipsize="end"
android:text="Description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</RelativeLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
CardsFragment.java
package com.example.musicassistant;
import android.animation.ArgbEvaluator;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public class CardsFragment extends Fragment {
ViewPager viewPager;
Adapter adapter;
List<Model> models;
Integer[] colors = null;
ArgbEvaluator argbEvaluator = new ArgbEvaluator();
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
models = new ArrayList<>();
models.add(new Model(R.drawable.brochure, "Brochure", "oooooo"));
models.add(new Model(R.drawable.sticker, "Sticker", "oooooo"));
models.add(new Model(R.drawable.poster, "Poster", "oooooo"));
models.add(new Model(R.drawable.namecard, "Namecard", "oooooo"));
adapter = new Adapter(models, getActivity());
viewPager = inflater.inflate(R.layout.fragment_cards, container, false).findViewById(R.id.viewPager);
viewPager.setAdapter(adapter);
viewPager.setPadding(130,0,130,0);
Integer[] colors_temp = {
getResources().getColor(R.color.color1),
getResources().getColor(R.color.color2),
getResources().getColor(R.color.color3),
getResources().getColor(R.color.color4)
};
colors = colors_temp;
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
if (position < (adapter.getCount() -1) && position < (colors.length -1)) {
viewPager.setBackgroundColor(
(Integer) argbEvaluator.evaluate(
positionOffset,
colors[position],
colors[position + 1]
)
);
} else {
viewPager.setBackgroundColor(colors[colors.length - 1]);
}
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
return inflater.inflate(R.layout.fragment_cards, container, false);
}
}
Adapter.java
package com.example.musicassistant;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.viewpager.widget.PagerAdapter;
import java.util.List;
public class Adapter extends PagerAdapter {
private List<Model> models;
private LayoutInflater layoutInflater;
private Context context;
public Adapter(List<Model> models, Context context) {
this.models = models;
this.context = context;
}
#Override
public int getCount() {
return models.size();
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return view.equals(object);
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
layoutInflater = LayoutInflater.from(context);
View view = layoutInflater.inflate(R.layout.item, container, false);
ImageView imageView;
TextView title, desc;
imageView = view.findViewById(R.id.image);
title = view.findViewById(R.id.title);
desc = view.findViewById(R.id.desc);
imageView.setImageResource(models.get(position).getImage());
title.setText(models.get(position).getTitle());
desc.setText(models.get(position).getDesc());
container.addView(view, 0);
return view;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
container.removeView((View)object);
}
}
Model.java
package com.example.musicassistant;
public class Model {
private int image;
private String title;
private String desc;
public Model(int image, String title, String desc) {
this.image = image;
this.title = title;
this.desc = desc;
}
public int getImage() {
return image;
}
public void setImage(int image) {
this.image = image;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
}
It is worth noting that the fragment itself is working, as the button in it is appearing correctly.
The only issue is that my cards are not showing up at all.
Any help would be greatly appreciated as this is driving me absolutely insane!
Thank you very much for your time I greatly appreciate it,
Roman
Inflate will create a new layout object(view object) eveytime you use it so this is one view layout
viewPager = inflater.inflate(R.layout.fragment_cards, container, false).findViewById(R.id.viewPager);
and you are returning a new view object which has nothing
return inflater.inflate(R.layout.fragment_cards, container, false);
so you need to store a single reference of view after inflating then use it and return it, as
View root = inflater.inflate(R.layout.fragment_cards, container, false).findViewById(R.id.viewPager);
viewPager = root.findViewById(R.id.viewPager);
// ... code
return root;

How do I set variables to true/false from a Listview of Checkboxes?

I created a listview with a custom adapter that allows me to have a list of items with checkboxes next to each item.
So I would like to look at the checkbox for the corresponding item in the list and see if it is checked and if it is, then set the value of boolean whiskey = false to true and so on for the other booleans.
It is very possible I have code in the wrong class or xml file, I've been trying to piece together things I've found on the internet. I'm new to android studio so its proving very difficult. I do have about a years worth of java experience though. I have all my code written in a working program on Eclipse, I am just having a hell of a time figuring out how to implement it into a working app.
Thanks in advance.
customAdapter.java
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import java.util.ArrayList;
public class customAdapter extends BaseAdapter {
private ArrayList<String> list = new ArrayList<String>();
private Context context;
public customAdapter(ArrayList<String> list, Context context) {
this.list = list;
this.context = context;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int pos) {
return list.get(pos);
}
public void setChecked(boolean isChecked){
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.activity2_listview, null);
}
//Handle TextView and display string from your list
TextView label = (TextView)view.findViewById(R.id.label);
label.setText(list.get(position));
//Handle buttons and add onClickListeners
CheckBox callchkbox = (CheckBox) view.findViewById(R.id.cb);
callchkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//update isChecked value to model class of list at current position
list.get(position).setChecked(isChecked);
}
});
return view;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
Main2Activity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.Arrays;
import android.widget.CheckBox;
public class Main2Activity extends AppCompatActivity {
boolean Whiskey, Bourbon, Rum, Gin, Vodka, Tequila = false;
String [] userIngredients = {"Whiskey", "Bourbon", "Rum", "Gin", "Vodka", "Tequila", "Club Soda", "Lemon-Lime Soda",
"Ginger ale", "Cola", "Still mineral water", "Tonic Water", "Orange Juice", "Cranberry Juice", "Grapefruit Juice",
"Tomato Juice", "Cream or Half and Half", "Milk", "Ginger Beer", "PineApple Juice", "Lemons", "Limes", "Oranges"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
ListView listView = (ListView) findViewById(R.id.userIngredients);
ArrayList<String> list = new ArrayList<String>(Arrays.asList(userIngredients));
listView.setAdapter(new customAdapter(list, Main2Activity.this));
}
}
activity_main2.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
tools:context=".Main2Activity"
android:id="#+id/linearLayout">
<ListView
android:layout_width="419dp"
android:layout_height="558dp"
android:id="#+id/userIngredients"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView2"
tools:layout_conversion_absoluteHeight="731dp"
tools:layout_conversion_absoluteWidth="411dp" />
<TextView
android:id="#+id/textView2"
android:layout_width="374dp"
android:layout_height="60dp"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:text="Check Your Ingredients"
android:textSize="24sp"
app:fontFamily="#font/cinzel"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>
activity2_listview.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/label"
android:layout_width="323dp"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:text="ingredient"
android:textSize="20sp" />
<CheckBox
android:id="#+id/cb"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
i think you can do it with a BaseAdapter as well, but i suggest to use a RecyclerView instead.
I used support-v4 and recyclerview-v7 libs as following:
(Make sure that you are not developing AndroidX - check your gradle.properties of the entire project. It is very similar but uses other libraries though.)
build.gradle
android {
compileSdkVersion 28
buildToolsVersion '28.0.3'
...
dependencies {
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support:support-v4:28.0.0'
implementation 'com.android.support:design:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.android.support:recyclerview-v7:28.0.0'
...
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.widget.RelativeLayout
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">
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Check Your Ingredients"
android:textAlignment="center" />
<android.support.v7.widget.RecyclerView
android:id="#+id/recycler_chooser"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" >
</android.support.v7.widget.RecyclerView>
</android.widget.RelativeLayout>
In the activity2_listview you might want to do more design to the xml. It looks very basic now.
activity2_listview.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/listviewtextlabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:text="ingredient"
android:textSize="20sp" />
<CheckBox
android:id="#+id/listviewcheckbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
In the main class we implement a callback-listener for our custom onItemAction function. We pass the listener with adapter.setActionListener(this); and add the adapter to the RecyclerViewer.
MainActivity.java
public class MainActivity extends AppCompatActivity implements CustomAdapter.ItemActionListener {
boolean Whiskey, Bourbon, Rum, Gin, Vodka, Tequila = false;
String [] userIngredients = {"Whiskey", "Bourbon", "Rum", "Gin", "Vodka", "Tequila", "Club Soda", "Lemon-Lime Soda",
"Ginger ale", "Cola", "Still mineral water", "Tonic Water", "Orange Juice", "Cranberry Juice", "Grapefruit Juice",
"Tomato Juice", "Cream or Half and Half", "Milk", "Ginger Beer", "PineApple Juice", "Lemons", "Limes", "Oranges"};
CustomAdapter adapter;
RecyclerView.LayoutManager layoutManager;
RecyclerView recyclerListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
try {
recyclerListView = (RecyclerView) findViewById(R.id.recycler_chooser);
ArrayList<String> list = new ArrayList<>();
list.addAll(Arrays.asList(userIngredients));
// use this setting to improve performance if you know that changes
// in content do not change the layout size of the RecyclerView
recyclerListView.setHasFixedSize(false);
layoutManager = new LinearLayoutManager(this);
recyclerListView.setLayoutManager(layoutManager);
System.out.println("list.size() " + list.size());
adapter = new CustomAdapter(list,MainActivity.this);
adapter.setActionListener(this);
recyclerListView.setAdapter(adapter);
} catch (Exception e){
e.printStackTrace();
}
}
// callback listener for your items
#Override
public void onItemAction(View view, CustomAdapter.CustomActions customAction, int position) {
final String itemName = adapter.getItem(position);
System.out.println(customAction + ": You clicked " + itemName + " on row number " + position);
switch(itemName){
case "Whiskey":
if(customAction== CustomAdapter.CustomActions.CHECK){
Whiskey=true;
}
else{
Whiskey=false;
}
System.out.println("Whiskey set to: " + Whiskey);
break;
case "Bourbon":
if(customAction== CustomAdapter.CustomActions.CHECK){
Bourbon=true;
}
else{
Bourbon=false;
}
System.out.println("Bourbon set to: " + Bourbon);
break;
//case xyz
// and so on
default:
System.out.println("Not programmed yet: " + itemName);
}
}
}
As said above i removed the BaseAdapter and replaced it with the RecyclerView. We had to implement a custom ViewHolder-class that contains each row in our RecyclerViewList. Within the ViewHolder we can call the method on our listener whenever a checkbox-change event occurs.
CustomAdapter.java
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
import java.util.ArrayList;
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.CustomViewHolder> {
//------ helper class for the viewholder
enum CustomActions{
CHECK,UNCHECK
}
// Provide a reference to the views for each row
public class CustomViewHolder extends RecyclerView.ViewHolder {
// each data item is just a string in this case
public TextView mTextView;
public CheckBox mCheckBox;
public CustomViewHolder(View v) {
super(v);
// the view element v is the whole linear layout element
CheckBox.OnCheckedChangeListener checkboxListenerForOneEntry = new CheckBox.OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton view, boolean isChecked) {
if (mItemActionListener != null) {
if(isChecked){
// this compoundbutton view element will be the checkbox
mItemActionListener.onItemAction(view, CustomActions.CHECK, getAdapterPosition());
}else{
mItemActionListener.onItemAction(view, CustomActions.UNCHECK, getAdapterPosition());
}
}
}
};
mTextView = v.findViewById(R.id.listviewtextlabel);
mCheckBox = v.findViewById(R.id.listviewcheckbox);
mCheckBox.setOnCheckedChangeListener(checkboxListenerForOneEntry);
}
}
//------
private ArrayList<String> list;
private Context context;
private LayoutInflater mInflater;
private ItemActionListener mItemActionListener;
public CustomAdapter(ArrayList<String> list, Context context) {
this.list = list;
this.context = context;
this.mInflater = LayoutInflater.from(this.context);
}
// allows clicks events to be caught
void setActionListener(ItemActionListener itemActionListener) {
this.mItemActionListener = itemActionListener;
}
// parent activity will implement this method to respond to click events
public interface ItemActionListener {
void onItemAction(View view, CustomActions customAction, int position);
}
// Create new views (invoked by the layout manager)
#Override
public CustomViewHolder onCreateViewHolder(ViewGroup parent,
int viewType) {
// create a new view
View v = mInflater.inflate(R.layout.activity2_listview, parent, false);
return new CustomViewHolder(v);
}
// Replace the contents of a view (invoked by the layout manager)
#Override
public void onBindViewHolder(CustomViewHolder holder, int position) {
// - get element from your dataset at this position
// - replace the contents of the view with that element
holder.mTextView.setText(list.get(position));
}
#Override // Return the size of your dataset (invoked by the layout manager)
public int getItemCount() {
return getCount();
}
public int getCount() {
return list.size();
}
public String getItem(int pos) {
return list.get(pos);
}
}
Feel free to use the code as you like.
For more info about the RecyclerView see the google docs: https://developer.android.com/guide/topics/ui/layout/recyclerview

How to make custom adapter?

I'm trying to make custom adapter for my small app, I got stuck in filling my rows with data, I can't find a good tutorial for that. I know how to use Simple Adapter and Array Adapter, but custom ones have some trouble.
I don't know how to implement it, and the online articles confused me, Please help me with the logic and what steps should I do implement.
package com.example.administrator.healthyfood;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ListView;
public class MainActivity extends AppCompatActivity {
ListView list;
String[] food = {"Dog","Cat","Cow","Fish","Frog","Bird","Rabbit","Horse","Chikcen"};
#Override
protected void onCreate(Bundle savedInstanceState) {
list = (ListView)findViewById(R.id.listView);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public class MyListViewAdapter extends BaseAdapter {
#Override
public int getCount() {
return food.lenght();
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
return null;
}
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" >
</ListView>
</RelativeLayout>
custom.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:layout_width="255dp"
android:layout_height="wrap_content"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Video1"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#339966"
android:textStyle="bold" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/detail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="video1"
android:textColor="#606060" />
</LinearLayout>
</LinearLayout>
<ImageView
android:id="#+id/img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_launcher" />
</LinearLayout>
</LinearLayout>
Your MainActivity.java -
package com.example.sample;
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class MainActivity extends Activity {
ListView l1;
String[] t1={"video1","video2"};
String[] d1={"lesson1","lesson2"};
int[] i1 ={R.drawable.ic_launcher,R.drawable.ic_launcher};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
l1=(ListView)findViewById(R.id.list);
l1.setAdapter(new dataListAdapter(t1,d1,i1));
}
class dataListAdapter extends BaseAdapter {
String[] Title, Detail;
int[] imge;
dataListAdapter() {
Title = null;
Detail = null;
imge=null;
}
public dataListAdapter(String[] text, String[] text1,int[] text3) {
Title = text;
Detail = text1;
imge = text3;
}
public int getCount() {
// TODO Auto-generated method stub
return Title.length;
}
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View row;
row = inflater.inflate(R.layout.custom, parent, false);
TextView title, detail;
ImageView i1;
title = (TextView) row.findViewById(R.id.title);
detail = (TextView) row.findViewById(R.id.detail);
i1=(ImageView)row.findViewById(R.id.img);
title.setText(Title[position]);
detail.setText(Detail[position]);
i1.setImageResource(imge[position]);
return (row);
}
}
}
Hope this is enough for you.
You can create a simple Adapter class using these simple steps
make a java class
public class Wallet_Adapter extends RecyclerView.Adapter<Wallet_Adapter.ViewHolder>
{
LayoutInflater inflater;
List<Wallet_Model> modelclasslists;
public Wallet_Adapter(Context ctx, List<Wallet_Model> modelclasslists)
{
this.inflater=LayoutInflater.from(ctx);
this.modelclasslists=modelclasslists;
}
#NonNull
#Override
public Wallet_Adapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view=inflater.inflate(R.layout.layout_wallet,parent,false);
return new Wallet_Adapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull Wallet_Adapter.ViewHolder holder, int position) {
holder.date.setText(modelclasslists.get(position).getDate());
holder.amount.setText(modelclasslists.get(position).getAmount());
holder.description.setText(modelclasslists.get(position).getDescription());
holder.type.setText(modelclasslists.get(position).getType());
}
#Override
public int getItemCount() {return modelclasslists.size(); }
public class ViewHolder extends RecyclerView.ViewHolder
{
TextView date,amount,description,type;
public ViewHolder(#NonNull View itemView)
{
super(itemView);
date=itemView.findViewById(R.id.dateans);
amount=itemView.findViewById(R.id.amountans);
description=itemView.findViewById(R.id.descriptionans);
type=itemView.findViewById(R.id.typeans);
}
}
}

Picasso not displaying images in GridView

I've read several posts having similar problems yet I still can't make the fix.
The app I'm trying to build is supposed to retrieve images from a link and display them. This is done through Picasso and is supposed to be displayed in GridView format.
Here is my MovieAdapter.java:
package com.example.android.popularmovies.utilities;
import android.app.Activity;
import android.content.Context;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import com.example.android.popularmovies.R;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
/**
* Created by Jonathan on 6/18/2017.
*/
public class MovieAdapter extends ArrayAdapter<String>{
Context mContext;
int mLayoutResourceId;
ArrayList<String> mData = new ArrayList<>();
public MovieAdapter(Context context, int layoutResourceId,
ArrayList<String> data) {
super(context, layoutResourceId, data);
mLayoutResourceId = layoutResourceId;
mContext = context;
mData = data;
}
public void setData(ArrayList<String> mGridData) {
mData=mGridData;
notifyDataSetChanged();
}
//TODO code is working. Posters arent displayed :(
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
convertView = inflater.inflate(mLayoutResourceId, parent, false);
ImageView image = (ImageView) convertView.findViewById(R.id.iv_moviePoster);
convertView.setTag(image);
try {
String poster = NetworkUtils.posterBuilder(mData.get(position));
Picasso.with(mContext).
load(poster).
into(image);
}
catch(NullPointerException e) { e.printStackTrace(); }
return image;
}
#Override
public int getCount() {
return mData.size();
}
#Nullable
#Override
public String getItem(int position) {
return mData.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
}
When running the code, nothing is displayed. Please help and thank you
Update
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
android:layout_height="match_parent"
android:layout_width="match_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<ImageView
android:id="#+id/iv_moviePoster"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/gv_movieData"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:columnWidth="100dp"
android:numColumns="2"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:stretchMode="columnWidth"
android:gravity="center" />
<ProgressBar
android:id="#+id/pb_loadingBar"
android:layout_width="42dp"
android:layout_height="42dp"
android:layout_gravity="center"
android:visibility="invisible"/>
</LinearLayout>
Permissions:
<uses-permission android:name="android.permission.INTERNET"/>

Custom GridView doesn't display data

I am trying to feed my custom GridView with data fetched from Facebook Graph API. This data is a list of Album objects containing the picture for the album of the current user and the name of the album.
Fetching data doesn't represent a problem since I can see it in the LOGCAT.
What seems to be a problem is my GridView Adapter I suppose, the program doesn't give any particular error and this makes me confused.
Note that the MainActivity which will not be displayed here serves only to connect a user via Facebook account (there is no problem in this Activity)
Here is my different classes :
----LoggedInActivity.java
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;
import com.facebook.AccessToken;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.login.LoginManager;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class LoggedInActivity extends Activity {
String name, surname, ID;
TextView nameOfUser;
Button logout;
GridView gridView;
GridViewAdapter gridViewAdapter;
List<Album> albumList = new ArrayList<Album>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle inBundle = getIntent().getExtras();
name = inBundle.getString("name");
surname = inBundle.getString("surname");
ID = inBundle.getString("ID");
setContentView(R.layout.activity_logged_in);
nameOfUser = (TextView) findViewById(R.id.name);
nameOfUser.setText(name + " " + surname);
logout = (Button) findViewById(R.id.logout);
gridView = (GridView) findViewById(R.id.myGridView);
albumList = getAlbums();
logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
LoginManager.getInstance().logOut();
Intent login = new Intent(LoggedInActivity.this, MainActivity.class);
startActivity(login);
finish();
}
});
gridViewAdapter = new GridViewAdapter(getBaseContext(), albumList);
gridView.setAdapter(gridViewAdapter);
}
public List<Album> getAlbums() {
albumList = new ArrayList<Album>();
GraphRequest request = GraphRequest.newGraphPathRequest(
AccessToken.getCurrentAccessToken(),
"/me/albums",
new GraphRequest.Callback() {
Album album = null;
#Override
public void onCompleted(GraphResponse response) {
JSONObject jsonDATA = response.getJSONObject();
JSONArray data = jsonDATA.optJSONArray("data");
for(int i = 0 ; i< data.length(); i++){
try {
JSONObject e = data.getJSONObject(i);
String name = e.optString("name");
JSONObject picture = e.getJSONObject("picture");
JSONObject dataOfPicture = picture.getJSONObject("data");
String url = dataOfPicture.optString("url");
album = new Album(name, url);
albumList.add(album);
Log.d("Mine",name + url);
} catch (JSONException e1) {
Toast.makeText(getBaseContext(), "Problem with JSON parsing", Toast.LENGTH_SHORT).show();
}
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "picture,name");
request.setParameters(parameters);
request.executeAsync();
return albumList;
}
}
------Album.java
public class Album {
public String album_name;
public String album_image;
public Album(String album_name, String album_image) {
this.album_name = album_name;
this.album_image = album_image;
}
public String getAlbum_name() {
return album_name;
}
public String getAlbum_image() {
return album_image;
}
public void setAlbum_name(String album_name) {
this.album_name = album_name;
}
public void setAlbum_image(String album_image) {
this.album_image = album_image;
}
}
-----GridViewAdapter.java
import android.content.Context;
import android.graphics.BitmapFactory;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.net.URL;
import java.util.List;
public class GridViewAdapter extends BaseAdapter {
private List<Album> albumList;
private Context context;
public GridViewAdapter(#NonNull Context context, #NonNull List<Album> objects) {
this.albumList = objects;
this.context = context;
}
#Override
public int getCount() {
return albumList.size();
}
#Nullable
#Override
public Album getItem(int position) {
return albumList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View v = convertView;
if(v==null){
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.item,null);
}
Album album = getItem(position);
ImageView imageView = (ImageView)v.findViewById(R.id.imageHolder);
TextView description = (TextView)v.findViewById(R.id.albumDesc);
try {
imageView.setImageBitmap(BitmapFactory.decodeStream((new URL(album.getAlbum_image())).openConnection().getInputStream()));
} catch (IOException e) {
Toast.makeText(context, "Problem with input output streams", Toast.LENGTH_SHORT).show();
}
description.setText(album.getAlbum_name());
return v;
}
}
------item.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/imageHolder"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_alignParentTop="true"
android:layout_gravity="center"
android:layout_weight="1"
app:srcCompat="#drawable/com_facebook_profile_picture_blank_square" />
<TextView
android:layout_width="wrap_content"
android:text="photo"
android:textSize="15sp"
android:id="#+id/albumDesc"
android:layout_below="#+id/imageHolder"
android:layout_marginLeft="20dp"
android:layout_height="wrap_content" />
</RelativeLayout>
------Activity_logged_in.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
tools:context="ichou.facebooktest.LoggedInActivity">
<LinearLayout
android:id="#+id/intro"
android:layout_width="368dp"
android:layout_height="40dp"
android:layout_marginLeft="0dp"
android:layout_marginRight="0dp"
android:paddingTop="2dp"
android:paddingBottom="2dp"
android:orientation="horizontal">
<TextView
android:layout_width="200dp"
android:layout_height="match_parent"
android:layout_marginTop="0dp"
android:paddingTop="10dp"
android:text="username"
android:id="#+id/name"/>
<Button
android:layout_width="70dp"
android:layout_height="35dp"
android:text="logout"
android:id="#+id/logout"/>
</LinearLayout>
<GridView
android:layout_below="#+id/intro"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/myGridView"
android:layout_marginTop="10dp"
android:paddingTop="2dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:numColumns="2"
android:columnWidth="150dp"
android:gravity="center"
android:horizontalSpacing="10dp"
android:verticalSpacing="10dp"
/>
</RelativeLayout>
write your code like in adapter below...
you do wrong line in inflate layout in getView() method
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View v = convertView;
if(v==null){
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.item,convertView, false);
}
Album album = getItem(position);
ImageView imageView = (ImageView)v.findViewById(R.id.imageHolder);
TextView description = (TextView)v.findViewById(R.id.albumDesc);
try {
imageView.setImageBitmap(BitmapFactory.decodeStream((new URL(album.getAlbum_image())).openConnection().getInputStream()));
} catch (IOException e) {
Toast.makeText(context, "Problem with input output streams", Toast.LENGTH_SHORT).show();
}
description.setText(album.getAlbum_name());
return v;
}

Categories

Resources