Android Custom ListView Adapter doesn't populate - java

Long time stack user, first time poster. I have followed several Custom ListView Adapter tutorials and have not been able to get this one to work (I have successfully created these adapters before). I have spent way too many hours trying to get this to work!!! Can someone please have a look and hopefully find the silly mistake that I made?
This is in MainActivity.java onCreate() to call the list
//Declaration for the list
private ArrayList<Consumption> meals = new ArrayList<Consumption>();
private RAdapter rAdapter;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_meal);
//This is the first of two listviews on the activity
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listItems);
ListView listView = (ListView) findViewById(R.id.listView1);
listView.setAdapter(adapter);
//This is the listview I am having problems with
ListView listView2 = (ListView) findViewById(R.id.resultList);
rAdapter = new RAdapter(this,meals);
listView2.setAdapter(rAdapter);
}
I have triple checked that meals has data, it does.
This is the RAdapter.java (The Custom Adapter) code:
public class RAdapter extends ArrayAdapter<Consumption>{
static class holder{
TextView rName;
EditText quan;
ImageButton delete;
}
private ArrayList<Consumption> meals;
private final Context context;
public RAdapter(Context context) {
super(context, R.layout.result_row);
this.context = context;
}
public RAdapter(Context context, ArrayList<Consumption> meals) {
super(context, R.layout.result_row);
this.context = context;
this.meals = meals;
}
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
holder h = null;
if (v == null) {
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
v = inflater.inflate(R.layout.result_row, parent, false);
h = new holder();
h.rName = (TextView) v.findViewById(R.id.resultName);
h.quan = (EditText) v.findViewById(R.id.resultGrams);
h.delete = (ImageButton) v.findViewById(R.id.resultDelete);
v.setTag(h);
}else{
h = (holder) v.getTag();
}
Consumption i = meals.get(position);
h.rName.setText(i.getShortName());
h.quan.setText(i.getQuantity());
return v;
}
}
Here is result_row.xml (The specific row to populate):
<?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="wrap_content" >
<ImageButton
android:id="#+id/resultDelete"
android:layout_marginLeft="10dp"
android:layout_width="35dp"
android:layout_height="35dp"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:src="#android:drawable/ic_notification_clear_all"
android:contentDescription="#string/meal_remove" />
<TextView
android:id="#+id/resultName"
android:layout_marginLeft="10dp"
android:layout_width="150dp"
android:layout_height="40sp"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/resultDelete" />
<EditText
android:id="#+id/resultQuantity"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_width="50dp"
android:layout_height="40sp"
android:inputType="numberDecimal"
android:layout_toRightOf="#+id/resultName"
android:layout_centerVertical="true" />
<TextView
android:id="#+id/resultGrams"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/resultQuantity"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:text="#string/grams" />
</RelativeLayout>
Here is activity_meal.xml (which has the listview "resultList" in it):
<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:background="#drawable/semislantedbacktransparent"
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=".MealActivity" >
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:orientation="horizontal" >
<ImageButton
android:id="#+id/translateButton"
android:layout_width="100dp"
android:layout_height="65dp"
android:background="#drawable/addtorecipe"
android:contentDescription="#string/dummy_button"
android:text="#string/button_add_recipe" />
</LinearLayout>
<SearchView
android:id="#+id/searchView1"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:background="#drawable/search"
android:focusable="true"
android:iconifiedByDefault="false"
android:onClick="enterTomInput"
android:queryHint="Search for food items"
android:showAsAction="always"
android:textColor="#000000" >
</SearchView>
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="150dp"
android:layout_alignLeft="#+id/searchView1"
android:layout_below="#+id/searchView1"
android:cacheColorHint="#color/black_overlay" >
</ListView>
<ListView
android:id="#+id/resultList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/linearLayout1"
android:layout_below="#+id/listView1" />
<ImageButton
android:id="#+id/completeButton"
android:layout_width="100dp"
android:layout_height="65dp"
android:layout_alignRight="#+id/resultList"
android:layout_alignTop="#+id/linearLayout1"
android:background="#drawable/completemeal"
android:contentDescription="#string/dummy_button" />
</RelativeLayout>
I can post a logcat, but there is no error message to report. I have tried putting System prints everywhere, but cannot figure the problem out.
Any help would be much appreciated!!

Just change following code and fill your arraylist with data.
public RAdapter(Context context, ArrayList<Consumption> meals) {
super(context, R.layout.result_row);
this.context = context;
this.meals = meals;
}
to
public RAdapter(Context context, ArrayList<Consumption> meals) {
super(context, R.layout.result_row,meals);
this.context = context;
this.meals = meals;
}
in your adapter class.

change your adapter like this
public class RAdapter extends ArrayAdapter<Consumption> {
private Activity activity;
private ArrayList<Consumption> meals;
private LayoutInflater inflater = null;
public RAdapter (Activity act, int resource, ArrayList<Consumption> arrayList) {
super(act, resource, arrayList);
this.activity = act;
this.meals= arrayList;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
view = inflater.inflate(R.layout.result_row, parent, false);
}
//remaining code
return view;
}
}
and call this adapter
rAdapter = new RAdapter(MainActivity.this,R.layout.result_row,meals);
listView2.setAdapter(rAdapter);

Related

Fragment viewpager No adapter attached; skipping layout

I tried a lot of solutions but no solution has worked for me.
I am getting data from the server and showing it inside a recycleview. The data shows fine but shows this error in the logcat
Access denied finding property "persist.vendor.log.tel_dbg"
E/RecyclerView: No adapter attached; skipping layout
E/RecyclerView: No adapter attached; skipping layout
sometimes when I refresh again and again the recyclerview becomes empty.
I am using viewpager consisting of 2 fragments inside a parent fragment.
this recycleview is using in a nested scrollview
some time data not showing
Code snippet:
homebuyer_adapter_recycler=new homebuyer_adapter_recycle(getActivity(), items);
LinearLayoutManager home = new LinearLayoutManager(getActivity());
home.setOrientation(LinearLayoutManager.VERTICAL);
allitemsgrid.setLayoutManager(home);
allitemsgrid.setAdapter(r);
Here is more about
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent,
final int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.items_view,parent,
false);
RecyclerView.LayoutParams lp = new
RecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
v.setLayoutParams(lp);
ViewHolder viewHolder = new ViewHolder(v);
HERE IS MY item view
<?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="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="3dp"
app:cardCornerRadius="6dp"
android:layout_marginBottom="3dp"
app:cardBackgroundColor="#color/white">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="150dp">
<com.makeramen.roundedimageview.RoundedImageView
android:layout_width="match_parent"
android:layout_height="150dp"
app:riv_corner_radius="6dp"
android:id="#+id/image_items"
android:scaleType="fitXY"
/>
<com.makeramen.roundedimageview.RoundedImageView
android:layout_width="match_parent"
android:layout_height="150dp"
app:riv_corner_radius="6dp"
android:background="#drawable/blackshade"
android:scaleType="fitXY"/>
<TextView
android:id="#+id/items_all"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="#dimen/_5sdp"
android:textColor="#color/white"
android:fontFamily="sans-serif-smallcaps"
android:paddingLeft="20dp"
android:text="Message" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingLeft="20dp"
android:text="Timing"
android:padding="#dimen/_5sdp"
android:textColor="#color/white"
android:layout_alignParentBottom="true"
android:fontFamily="#font/mylight"
android:layout_alignParentRight="true"
android:textSize="10dp"
android:id="#+id/shoptimming"/>
</RelativeLayout>
<TextView
android:id="#+id/name_item"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:alpha="0.6"
android:fontFamily="#font/arimo_bold"
android:paddingLeft="20dp"
android:text="Name"
android:textColor="#color/black"
android:textSize="17dp"
/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="2dp"
android:orientation="horizontal">
<TextView
android:id="#+id/minumum_order"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:layout_weight="1"
android:drawablePadding="10dp"
android:fontFamily="sans-serif"
android:paddingLeft="20dp"
android:text="Minimum " />
<TextView
android:id="#+id/price_item"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:fontFamily="sans-serif"
android:gravity="left"
android:paddingLeft="20dp"
android:text="charges"
/>
</LinearLayout>
</LinearLayout>
</androidx.cardview.widget.CardView>
</LinearLayout>
Here is my adapter class
public class homebuyer_adapter_recycle extends RecyclerView.Adapter<homebuyer_adapter_recycle.ViewHolder> {
private ArrayList<seller_information> listData;
private LayoutInflater layoutInflater;
int lastpostition=-1;
Context context;
public homebuyer_adapter_recycle(Context aContext, ArrayList<seller_information> listData) {
this.listData = listData;
layoutInflater = LayoutInflater.from(aContext);
context=aContext;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder
(#NonNull ViewGroup parent, final
int viewType) {
View v = LayoutInflater.from(parent.getContext()).
inflate(R.layout.items_view,parent, false);
ViewHolder viewHolder = new ViewHolder(v);
Log.i("inadapter","calling time");
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
phone_number_shop = listData.get(viewType).getPhonenumber();
homebuyer.Delivery_charges_shop =
listData.get(viewType).getDiliveryfee();
homebuyer.Shop_name = listData.get(viewType).getShopname();
homebuyer.minimum_order = listData.get(viewType).getMinorder();
//profession=items.get(i).getName();
// Toast.makeText(getActivity(),phn,Toast.LENGTH_SHORT).show();
all_and_cetegory_items items = new all_and_cetegory_items();
Bundle b = new Bundle();
b.putString("phone",homebuyer.phone_number_shop);
items.setArguments(b);
FragmentTransaction fragmentTransaction =
((AppCompatActivity)context).getSupportFragmentManager()
.beginTransaction();
fragmentTransaction.replace(R.id.nav_host_fragment, items);
fragmentTransaction.addToBackStack(null).commit();
}
});
return viewHolder;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.name.setText(listData.get(position).getShopname());
//
Picasso.with(context).load(listData.get(position)
.getShopimage()).into(holder.shopimage);
Glide.with(context).load(listData.get(position).getShopimage())
.into(holder.shopimage);
holder.dilivery.setText("Rs "+listData.get(position).getDiliveryfee()+"
Delivery fee");
holder.minorder.setText("Rs "+listData.get(position).getMinorder()+" minimum");
holder.items.setText(listData.get(position).getShopmessage());
holder.time.setText("Service Available
"+listData.get(position).getStartingtime()+" to
"+listData.get(position).getEndingtime());
Log.i("inadapter","calling time"+listData.get(position).getShopname());
}
#Override
public int getItemCount() {
return listData.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
TextView name;
TextView dilivery;
TextView items;
TextView minorder;
TextView time;
ImageView shopimage;
public ViewHolder(#NonNull View v) {
super(v);
name = (TextView) v.findViewById(R.id.name_item);
dilivery = (TextView) v.findViewById(R.id.price_item);
minorder = (TextView) v.findViewById(R.id.minumum_order);
items=(TextView)v.findViewById(R.id.items_all);
time=(TextView)v.findViewById(R.id.shoptimming);
shopimage=(ImageView) v.findViewById(R.id.image_items);
}
}
}
In error it is saying that the Adapter for RecylerView is not attached. So, try to add adapter to the layout using:
recyclerView.setAdapter(categoryAdapter);
I am assuming homebuyer_adapter_recycler is your adapter.
According to that, you haven't really set your adapter as the logcat is specifying.
Add the below code instead of allitemsgrid.setAdapter(r);
allitemsgrid.setAdapter(homebuyer_adapter_recycler);
If my assumption or suggestion is wrong, it is okay. It is probably because your question is not very clear and does not provide the necessary details. Please provide more details such as the adapter class code and what is allitemsgrid, homebuyer_adapter_recycler and r.

Android Studio: W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED

I am trying to make a movie list, but it only shows a white screen with the app name. Apparently, I have a very similar program to this and it runs perfectly fine. This is what I get when I run the program.
W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
I found someone saying that this error happens if there is an error in xml codes, but I will still put my java codes as well.
public class MainActivity extends AppCompatActivity {
private ListView mListView;
private Context mContext;
ArrayList<Movie> movieList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = this;
final ArrayList<Movie> movieList = Movie.getMoviesFromFile("movies.json", this);
MovieAdapter adapter = new MovieAdapter(this, movieList);
mListView = findViewById(R.id.movie_list_view);
mListView.setAdapter(adapter);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Movie selectedMovie = movieList.get(i);
Intent detailIntent = new Intent(mContext, MovieDetailActivity.class);
detailIntent.putExtra("title", selectedMovie.title);
detailIntent.putExtra("description", selectedMovie.description);
detailIntent.putExtra("poster", selectedMovie.poster);
startActivity(detailIntent);
}
});
}
The following is my adapter.
public class MovieAdapter extends BaseAdapter{
private Context mContext;
private ArrayList<Movie> mMovieList;
private LayoutInflater mInflater;
public MovieAdapter(Context mContext, ArrayList<Movie> mMovieList){
this.mContext = mContext;
this.mMovieList = mMovieList;
mInflater = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount(){return mMovieList.size();}
#Override
public Object getItem(int pos){return mMovieList.get(pos);}
#Override
public long getItemId(int pos){return pos;}
#Override
public View getView(int pos, View convertView, ViewGroup parent){
ViewHolder holder;
if(convertView == null){
convertView = mInflater.inflate(R.layout.list_item_movie, parent, false);
holder = new ViewHolder();
holder.titleTextView = convertView.findViewById(R.id.title);
holder.charactersTextView = convertView.findViewById(R.id.main_characters);
holder.descriptionTextView = convertView.findViewById(R.id.description);
holder.thumbnailImageView = convertView.findViewById(R.id.poster);
convertView.setTag(holder);
} else{
holder = (ViewHolder)convertView.getTag();
}
TextView titleTextView = holder.titleTextView;
TextView descriptionTextView = holder.descriptionTextView;
TextView charactersTextView = holder.charactersTextView;
ImageView thumbnailImageView = holder.thumbnailImageView;
Movie movie = (Movie)getItem(pos);
titleTextView.setText(movie.title);
titleTextView.setTextSize(20);
charactersTextView.setText(movie.main_characters);
charactersTextView.setTextSize(13);
descriptionTextView.setText(movie.description);
descriptionTextView.setTextSize(9);
Picasso.with(mContext).load(movie.poster).into(thumbnailImageView);
return convertView;
}
private static class ViewHolder{
public TextView titleTextView;
public TextView descriptionTextView;
public ImageView thumbnailImageView;
public TextView charactersTextView;
}
}
And the followings are the xml codes.
activity_main.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="com.example.user.junepyolee_miniapp1.MainActivity">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/movie_list_view" />
list_item_movie.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/poster"
android:layout_width="90dp"
android:layout_height="140dp"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="4dp"
android:layout_marginTop="6dp"
android:layout_marginBottom="6dp"
android:layout_centerVertical="true"
android:scaleType="fitCenter"
android:contentDescription="This is a thumbnail"
app:srcCompat="#mipmap/ic_launcher" />
<RelativeLayout
android:id="#+id/movie_list_text_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/poster"
android:layout_alignParentTop="false"
android:layout_toRightOf="#+id/poster">
<TextView
android:id="#+id/title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="3dp"
android:text="Title"
android:textSize="20sp" />
<TextView
android:id="#+id/description"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/title"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="3dp"
android:maxLines="3"
android:text="description"
android:textSize="9sp" />
<TextView
android:id="#+id/main_characters"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignEnd="#+id/description"
android:layout_below="#+id/description"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="3dp"
android:text="characters max 3 people"
android:textSize="13sp" />
<TextView
android:id="#+id/hasSeen"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/main_characters"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="3dp"
android:text="has seen?"
android:textSize="11sp" />
</RelativeLayout>
Does anyone have a solution for this one?
This is just a warning, and since it retries without the configuration option without (I am assuming from your comments) a followup error, this is not the source of your problem.
It's not a bad guess, since this is for an OpenGL-related class (android/opengl/EGL14), but it's not the source of your problem.
You can read more about EGL at https://www.khronos.org/egl.

custom listview on fragment - can't use getActivity()

I am trying to add delete button next to my item details basing on this answer.
I tried it on a new project, it works perefect:
and when I click delete, I delete the item.
sadly, I tried to use it in my own project when my listView is in calendar_tab.xml. calendar_tab uses CompactCalendarTab.java - fragment class.
so Android Studio errored:
E:\Downloads\MyCustomAdapter.java
Error:(49, 63) error: cannot find symbol method getSystemService(String)
I tried to change
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
to
LayoutInflater inflater = (LayoutInflater)getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
but with no luck.
custom_listview.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="match_parent" >
<TextView
android:id="#+id/list_item_string"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:paddingLeft="8dp"
android:textSize="18sp"
android:textStyle="bold" />
<Button
android:id="#+id/delete_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginRight="5dp"
android:text="Delete" />
calendar_tab.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:id="#+id/calendar_tab"
android:layout_height="match_parent"
>
<RelativeLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/toolbar_calendar"
android:background="#color/teal_300"
android:layout_alignParentTop="true"
android:padding="10sp"
android:layout_alignParentStart="true">
<ImageButton
android:id="#+id/back_button"
android:src="#mipmap/ic_arrow_back_black_24dp"
android:background="#null"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:onClick="goBackmain"
/>
<ImageButton
android:id="#+id/next_button"
android:src="#mipmap/ic_keyboard_arrow_left_black_24dp"
android:background="#null"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toLeftOf="#+id/showdate"
android:layout_toStartOf="#+id/showdate" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:textSize="25sp"
android:textStyle="bold"
android:textColor="#color/black"
android:id="#+id/showdate"
android:layout_alignBaseline="#+id/prev_button"
android:layout_alignBottom="#+id/prev_button"
android:layout_centerHorizontal="true" />
<ImageButton
android:id="#+id/prev_button"
android:src="#mipmap/ic_keyboard_arrow_right_black_24dp"
android:background="#null"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toRightOf="#+id/showdate"
android:layout_toEndOf="#+id/showdate" />
</RelativeLayout>
<com.github.sundeepk.compactcalendarview.CompactCalendarView
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/compactcalendar_view"
android:layout_width="fill_parent"
android:layout_height="250dp"
app:compactCalendarTargetHeight="250dp"
app:compactCalendarTextSize="12sp"
app:compactCalendarBackgroundColor="#null"
app:compactCalendarTextColor="#color/blue_grey_700"
app:compactCalendarCurrentSelectedDayBackgroundColor="#color/teal_300"
app:compactCalendarCurrentDayBackgroundColor="#color/teal_600"
app:compactCalendarCurrentDayIndicatorStyle="fill_large_indicator"
app:compactCalendarEventIndicatorStyle="small_indicator"
app:compactCalendarOtherMonthDaysTextColor="#534c4c"
app:compactCalendarShouldSelectFirstDayOfMonthOnScroll="true"
android:layout_below="#+id/toolbar_calendar"
/>
<ListView
android:id="#+id/bookings_listview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/compactcalendar_view"
>
</ListView>
my fragment:
public class CompactCalendarTab extends Fragment {
final ListView bookingsListView = (ListView) v.findViewById(R.id.bookings_listview);
adapter = new ArrayAdapter<>(getContext(), android.R.layout.simple_list_item_1, mutableBookings);
final ArrayList<String> list = new ArrayList<>();
final MyCustomAdapter adapter = new MyCustomAdapter(list, this);
bookingsListView.setAdapter(adapter);
compactCalendarView = (CompactCalendarView)
v.findViewById(R.id.compactcalendar_view);
}
my custom adapter:
public class MyCustomAdapter extends BaseAdapter implements ListAdapter {
private ArrayList<String> list = new ArrayList<String>();
private CompactCalendarTab context;
public MyCustomAdapter(ArrayList<String> list, CompactCalendarTab context) {
this.list = list;
this.context = context;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int pos) {
return list.get(pos);
}
#Override
public long getItemId(int pos) {
return 0;
//just return 0 if your list items do not have an Id variable.
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater = (LayoutInflater)getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.custom_listview, null);
}
//Handle TextView and display string from your list
TextView listItemText = (TextView)view.findViewById(R.id.list_item_string);
listItemText.setText(list.get(position));
//Handle buttons and add onClickListeners
Button deleteBtn = (Button)view.findViewById(R.id.delete_btn);
deleteBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
//do something
list.remove(position); //or some other task
notifyDataSetChanged();
}
});
return view;
}
}
Change this line
LayoutInflater inflater = (LayoutInflater)getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
To this
LayoutInflater inflater = LayoutInflater.from(parent.getContext());

NullPointException in ListView when getting button

I am having a weird problem and can't seem to find whats causing it. Every view component in my ArrayAdapter is being located in the getView method except my button which is causes a NullPointerException.
Adapter:
public class ItemAdapter extends ArrayAdapter<Item>{
private Context context;
private int resource;
private List<Item> list;
public ItemAdapter(Context context, int resource, List<Item> list)
{
super(context, resource, list);
this.context = context;
this.resource = resource;
this.list = list;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
if (convertView == null)
convertView = LayoutInflater.from(context).inflate(resource, parent,false);
TextView name = (TextView) convertView.findViewById(R.id.itemName);
ImageView itemImg = (ImageView) convertView.findViewById(R.id.itemImg);
Button addToCart = (Button) convertView.findViewById(R.id.button1);
final Item item = list.get(position);
name.setText(item.getName());
UrlImageViewHelper.setUrlDrawable(itemImg, item.getPicture());
addToCart.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View view)
{
Toast.makeText(context, "Clicked", Toast.LENGTH_LONG).show();
}
});
return convertView;
}
}
Fragment with listview
#InjectView(R.id.itemList) private ListView listView;
#Inject private ItemDao dao;
private ArrayAdapter<Item> adapter;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
return inflater.inflate(R.layout.fragment_shop, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState)
{
super.onViewCreated(view, savedInstanceState);
dao.open();
List<Item> items = dao.findAll();
dao.close();
adapter = new ItemAdapter(getActivity(),R.layout.list_product_item, items);
listView.setAdapter(adapter);
}
list_product_item
<?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="horizontal"
android:paddingBottom="5dp"
android:paddingLeft="10dp"
android:paddingRight="10dp"
android:paddingTop="5dp" >
<ImageView
android:id="#+id/itemImg"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_marginRight="5dp"
android:scaleType="centerCrop" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/itemName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/itemStoreName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
<Button
android:id="#+id/button1"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
Now the call to convertView.findViewById(R.id.button1) returns a null instance. What is the cause of this and how can I fix it.
do you have right the name of the layout?
adapter = new GroceryItemAdapter(getActivity(), R.layout.list_textview, items);
vs.
list_product_item
(I am assuming this is the file name for R.layout.list_product_item)
Instead of getting the layout inflater using the from method try initializing the inflater in the constructor..
mInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
in the getView
convertView = mInflater.inflate(your layout, null);

setOnItemClickListener is not working for ArrayAdapter<ImageView>

When i try to click on items in the list it doesnt go through the onItemClick method.
GridViewAdapter.java
public class GridViewAdapter extends ArrayAdapter<ImageItem>{
private Context context;
private int layoutResourceId;
private ArrayList<ImageItem> data = new ArrayList<ImageItem>();
public GridViewAdapter(Context context, int layoutResourceId,
ArrayList<ImageItem> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder = null;
if (row == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new ViewHolder();
holder.imageTitle = (TextView) row.findViewById(R.id.text);
holder.image = (ImageView) row.findViewById(R.id.image);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
ImageItem item = data.get(position);
holder.imageTitle.setText(item.getTitle());
holder.image.setImageBitmap(item.getImage());
return row;
}
static class ViewHolder {
TextView imageTitle;
ImageView image;
}
}
MainActivity.java
public class MainActivity extends Activity {
private GridView gridView;
private GridViewAdapter customGridAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
gridView = (GridView) findViewById(R.id.gridView);
customGridAdapter = new GridViewAdapter(this, R.layout.row_grid, getData());
gridView.setAdapter(customGridAdapter);
Log.d("yyoyoyoyo", "jhgvkbkhbjkhbj");
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
Toast.makeText(MainActivity.this, position + "#Selected",
Toast.LENGTH_SHORT).show();
}
});
}
private ArrayList<ImageItem> getData() {
final ArrayList<ImageItem> imageItems = new ArrayList<ImageItem>();
// retrieve String drawable array
TypedArray imgs = getResources().obtainTypedArray(R.array.image_ids);
for (int i = 0; i < imgs.length(); i++) {
Bitmap bitmap = BitmapFactory.decodeResource(this.getResources(),
imgs.getResourceId(i, -1));
imageItems.add(new ImageItem(bitmap, "Image#" + i));
}
return imageItems;
}
}
row_grid.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:orientation="vertical"
android:padding="5dp"
android:clickable="true"
android:background="#drawable/grid_color_selector"
android:focusable="false"
android:focusableInTouchMode="false"
android:descendantFocusability="blocksDescendants"
>
<ImageView
android:id="#+id/image"
android:layout_width="100dp"
android:layout_height="100dp"
android:focusable="false"
android:focusableInTouchMode="false"
>
</ImageView>
<TextView
android:id="#+id/text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"
android:gravity="center"
android:textSize="12sp"
android:focusable="false"
android:focusableInTouchMode="false"
>
</TextView>
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:background="#f0f0f0"
android:clickable="false"
android:descendantFocusability="blocksDescendants"
tools:context=".MainActivity" >
<GridView
android:id="#+id/gridView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:columnWidth="100dp"
android:gravity="center"
android:numColumns="auto_fit"
android:verticalSpacing="5dp"
android:drawSelectorOnTop="true"
android:stretchMode="columnWidth"
android:descendantFocusability="blocksDescendants"
>
</GridView>
</RelativeLayout>
I have tried most of the solutions regarding this topic on StackOverFlow none of them worked for me. This app lists all the images but when you click onItemClick isnt fired. Probably there is something wrong with my code.
Thank you!!
Remove android:clickable="true" in row_grid.xml. and add android:clickable="true" in activity_main.xml
Also remove the
android:focusable="false"
android:focusableInTouchMode="false"
As row_grid.xml is clickable, it blocks the grid's onclick listener from responding.

Categories

Resources