CustomSquare layout null pointer exception [duplicate] - android

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I am facing issue when i try to access the textview id from layout and set that id in my adapter class. It gives null pointer exception .How do I access the textview in adapter class.
Following is the code
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/gridCatalogProductContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:descendantFocusability="blocksDescendants"
android:orientation="vertical"
android:padding="2dp">
<com.android.ordering.newui.CustomSquareLayout
android:id="#+id/frame"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
>
<ImageView
android:id="#+id/gridViewImage"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:adjustViewBounds="true"
android:scaleType="fitXY"
android:src="#drawable/catalog_image_selector" />
<TextView
android:id="#+id/gridCatalogProducttNametextView"
android:layout_width="#dimen/image_width"
android:layout_height="#dimen/image_height"
android:layout_gravity="center"
android:background="#color/header_background"
android:fontFamily="serif"
android:gravity="center"
android:padding="5dp"
android:text="New Text"
android:textColor="#color/white"
android:textSize="18sp" />
<TextView
android:id="#+id/gridViewImageTitle"
android:layout_width="#dimen/catalog_image_size"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:layout_marginBottom="10dp"
android:gravity="center"
android:maxLines="1"
android:visibility="gone"
android:singleLine="false"
android:text=""
android:textAppearance="#style/white_text_appearance"
android:textSize="#dimen/grid_item_text_view_size" />
</com.android.emobilepos.ordering.newui.CustomSquareLayout>
</FrameLayout>
Below is my complete adapter class code where i got the crash when trying to set data in textview.
public class ProductCatalogAdapter extends CursorAdapter {
private final String attrToDisplay;
private final DisplayImageOptions options;
private OrderingMainCallback callback;
private LayoutInflater inflater;
MyPreferences preferences;
private ImageLoader imageLoader;
public ProductCatalogAdapter(OrderingMainCallback callback, Context context, Cursor c, boolean autoRequery) {
super(context, c, autoRequery);
this.callback = callback;
inflater = LayoutInflater.from(context);
preferences = new MyPreferences(context);
this.imageLoader = ImageLoader.getInstance();
File cacheDir = new File(preferences.getCacheDir());
if (!cacheDir.exists())
cacheDir.mkdirs();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context).memoryCacheExtraOptions(100, 100)
.discCacheExtraOptions(1000, 1000, Bitmap.CompressFormat.JPEG, 100, null).discCache(new UnlimitedDiscCache(cacheDir)).build();
imageLoader.init(config);
imageLoader.handleSlowNetwork(true);
attrToDisplay = preferences.getPreferencesValue(MyPreferences.pref_attribute_to_display);
options = new DisplayImageOptions.Builder().resetViewBeforeLoading(true).displayer(new SimpleBitmapDisplayer()).cacheOnDisc(true)
.imageScaleType(ImageScaleType.IN_SAMPLE_INT)
.showImageOnLoading(R.drawable.loading_image)
// .showImageForEmptyUri(R.drawable.no_image)
.build();
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View retView;
ViewHolder holder = new ViewHolder();
retView = inflater.inflate(R.layout.catalog_listview_adapter, parent, false);
holder.title = retView.findViewById(R.id.gridViewImageTitle);
holder.itemImage = retView.findViewById(R.id.gridViewImage);
holder.productNameTxt = retView.findViewById(R.id.gridCatalogProducttNametextView);
holder.prodNameIdx = cursor.getColumnIndex(attrToDisplay);
holder.prodIdIdx = cursor.getColumnIndex("_id");
holder.prodImgNameIdx = cursor.getColumnIndex("prod_img_name");
retView.setTag(holder);
return retView;
}
#Override
public void bindView(View view, Context context, final Cursor cursor) {
final ViewHolder holder = (ViewHolder) view.getTag();
holder.productNameTxt.setText(cursor.getString(holder.prodNameIdx));
holder.productNameTxt.setVisibility(View.INVISIBLE);
holder.title.setText(cursor.getString(holder.prodNameIdx));
String urlLink = cursor.getString(holder.prodImgNameIdx);
// holder.itemImage.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// if (preferences.isFastScanningMode()) {
// callback.addProduct(cursor.getString(holder.prodIdIdx));
// }
// }
// });
imageLoader.displayImage(urlLink, holder.itemImage, options, new ImageLoadingListener() {
#Override
public void onLoadingStarted(String s, View view) {
if (TextUtils.isEmpty(s)) {
holder.productNameTxt.setVisibility(View.VISIBLE);
holder.itemImage.setVisibility(View.GONE);
}else {
holder.productNameTxt.setVisibility(View.INVISIBLE);
holder.itemImage.setVisibility(View.VISIBLE);
}
}
#Override
public void onLoadingFailed(String s, View view, FailReason failReason) {
holder.productNameTxt.setVisibility(View.VISIBLE);
holder.itemImage.setVisibility(View.GONE);
}
#Override
public void onLoadingComplete(String s, View view, Bitmap bitmap) {
if (TextUtils.isEmpty(s)) {
holder.productNameTxt.setVisibility(View.VISIBLE);
holder.itemImage.setVisibility(View.GONE);
}else {
holder.productNameTxt.setVisibility(View.INVISIBLE);
holder.itemImage.setVisibility(View.VISIBLE);
}
}
#Override
public void onLoadingCancelled(String s, View view) {
}
});
if(TextUtils.isEmpty(urlLink)){
}
}
public class ViewHolder {
CustomSquareLayout customSquareLayout;
TextView title, productNameTxt;
ImageView itemImage;
int prodNameIdx;
public int prodIdIdx;
int prodImgNameIdx;
}
}

<com.android.ordering.newui.CustomSquareLayout
android:id="#+id/frame"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
>
</com.android.emobilepos.ordering.newui.CustomSquareLayout>
Your CustomSquareLayout start and end is not same i.e the package path is different and should be same.

Related

RecyclerView shows Strings but not Images

I have a SQLite database and want to search Items thorugh DB and then showing the items on recyclerView. Everything looking fine but recyclerView not showing the pictures, But somehow It shows the Strings
Normally pictures I saved inside the SQLite as BLOB should be displayed on the left.
Here is SearchFragment (Where I make the search and start recyclerView to display items)
public class SearchFragment extends Fragment {
Button searchbutton;
EditText editText;
View v;
Cursor cursor;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_search, container, false);
addListenerOnButton(v);
return v;
}
private void addListenerOnButton(View v) {
searchbutton = v.findViewById(R.id.searchfragment_button);
editText = v.findViewById(R.id.searchfragment_edittext);
searchbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String keystring = editText.getText().toString();
if(keystring.isEmpty())
Toast.makeText(getContext(),R.string.empty_search ,Toast.LENGTH_LONG).show();
else
new FoodQuery().execute(keystring);
}
});
}
//Place I start the search on background
private class FoodQuery extends AsyncTask<String, Void, Void>{
#Override
protected Void doInBackground(String [] keys) {
String name_col;
DietAppDatabaseHelper daDBHelper;
SQLiteDatabase daDB;
daDBHelper = new DietAppDatabaseHelper(getContext());
try {
daDB = daDBHelper.getReadableDatabase();
if (Locale.getDefault().getLanguage() == "tr")
name_col = "name_tr";
else
name_col = "name_eng";
String query = "SELECT * FROM food_data WHERE " //Query here
+ name_col + " LIKE ?" ;
cursor = daDB.rawQuery(query, new String[]{"%" + keys[0] + "%"});
viewResults(name_col);
daDB.close();
} catch (SQLiteException e){
Log.d("SearchFragment", "doInBackground: " + e);
}
return null;
}
}
private void viewResults(String lang) {
int name_col = -1; //For language issues not important
if(lang == "name_tr")
name_col = 1;
else if(lang == "name_eng")
name_col = 2;
ArrayList<String> tmpnames = new ArrayList<>(); //I put pictures to byte[] and names to String Arraylist here
ArrayList<byte[]> tmppictures = new ArrayList<>();
if(cursor.moveToFirst()){
tmpnames.add(cursor.getString(name_col));
tmppictures.add(cursor.getBlob(5));
while(cursor.moveToNext()){
tmpnames.add(cursor.getString(name_col));
tmppictures.add(cursor.getBlob(5));
}
}
else {
Looper.prepare();
Toast.makeText(getContext(), R.string.no_food_found, Toast.LENGTH_LONG).show(); //To prevent empty search
}
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
RecyclerView recyclerView = v.findViewById(R.id.recycler_view);
SearchResultAdapter adapter = new SearchResultAdapter(getContext(), tmppictures, tmpnames);
recyclerView.setLayoutManager(new LinearLayoutManager(getContext(), LinearLayoutManager.VERTICAL, false));
recyclerView.setAdapter(adapter);
}
});
}
}
Layout File of SearchFragment
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
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"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".fragments.SearchFragment"
android:id="#+id/fragment_search">
<Button
android:id="#+id/searchfragment_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="60dp"
android:layout_marginEnd="4dp"
android:layout_marginRight="4dp"
android:text="#string/nav_search"
android:textColor="#FFFFFF"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent"/>
<EditText
android:id="#+id/searchfragment_edittext"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="64dp"
android:ems="10"
android:inputType="textPersonName"
app:layout_constraintEnd_toStartOf="#+id/searchfragment_button"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="124dp"
app:layout_constraintTop_toTopOf="parent"
tools:layout_editor_absoluteX="0dp">
</androidx.recyclerview.widget.RecyclerView>
</androidx.constraintlayout.widget.ConstraintLayout>
Here is the adapter
public class SearchResultAdapter extends RecyclerView.Adapter<SearchResultAdapter.ViewHolder>{
private ArrayList<byte[]> foodimages;
private ArrayList<String> foodnames;
private Context context;
public SearchResultAdapter(Context context, ArrayList<byte[]> foodimages, ArrayList<String> foodnames) {
this.foodimages = new ArrayList<>(foodimages);
this.foodnames = new ArrayList<>(foodnames);
this.context = context;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.search_result_item, parent, false);
ViewHolder holder = new ViewHolder(view);
return holder;
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.foodname.setText(foodnames.get(position));
holder.foodimage.setImageBitmap(BitmapFactory.decodeByteArray(foodimages.get(position), 0, foodimages.size()));
}
#Override
public int getItemCount() {
return foodnames.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
ImageView foodimage;
TextView foodname;
RelativeLayout parentLayout;
public ViewHolder(#NonNull View itemView) {
super(itemView);
foodimage = itemView.findViewById(R.id.food_seacrh_image);
foodname = itemView.findViewById(R.id.food_search_name);
parentLayout = itemView.findViewById(R.id.search_item);
}
}
}
Lastly, the layout of my item to use in recyclerView
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="15dp"
android:id="#+id/search_item">
<ImageView
android:id="#+id/food_seacrh_image"
android:layout_width="100dp"
android:layout_height="100dp"
/>
<TextView
android:id="#+id/food_search_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/food_seacrh_image"
android:textColor="#FFFFFF"
android:layout_centerVertical="true"
android:layout_marginLeft="30dp"
android:textSize="17sp"
android:layout_toEndOf="#+id/food_seacrh_image"
android:layout_marginStart="30dp" />
It seems like the problem could be the line:
holder.foodimage.setImageBitmap(BitmapFactory.decodeByteArray(foodimages.get(position), 0, foodimages.size()));
Should probably be:
holder.foodimage.setImageBitmap(BitmapFactory.decodeByteArray(foodimages.get(position), 0, foodimages.get(position).size));
The third param on decodeByteArray should be the length (in bytes) of the image, you are passing in the actual number of images.

Why these random marks are appearing in every recyclerview and viewpager items?

I have 2 recycler views and a view pager in a fragment.
Everything else works fine but both recycler view items are showing a random mark on the upper left corner of every items. And same thing is happening for the view pager items.
This fragment is in a fragment activity and view pager is using pager adapter. And I am using Picasso library to load images on the items and also using network policy to cache the images in disk.
recycler view items appearing like this
view pager items appearing like this
Recycler View adapter
public class CourseListAdapter extends RecyclerView.Adapter<CourseListAdapter.CourseListViewHolder> {
public static final int HOME_PAGE = 1;
public static final int DISPLAY_COURSE = 2;
private Picasso mPicasso;
private List<DisplayCourse> courseList;
private static final String TAG = "CourseListAdapter";
private OnItemClickListener mListener;
public interface OnItemClickListener {
void onItemClick(int position, View view);
}
private String mSender;
public void setOnItemClickListener(OnItemClickListener listener) {
mListener = listener;
}
public CourseListAdapter(List<DisplayCourse> courseList, String sender) {
this.courseList = courseList;
this.mSender = sender;
mPicasso = Picasso.get();
}
#NonNull
#Override
public CourseListViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
switch (viewType) {
case 1:
View view1 = inflater.inflate(R.layout.recom_course_home_layout, parent, false);
return new CourseListViewHolder(view1, mListener);
case 2:
View view2 = inflater.inflate(R.layout.display_course_layout, parent, false);
return new CourseListViewHolder(view2, mListener);
default:
View view3 = inflater.inflate(R.layout.section_video_item_layout, parent, false);
return new CourseListViewHolder(view3, mListener);
}
}
#Override
public void onBindViewHolder(#NonNull CourseListViewHolder holder, int position) {
holder.title.setText(courseList.get(position).getCourseTitle());
mPicasso.load(courseList.get(position).getThumbnailURL())
.networkPolicy(NetworkPolicy.OFFLINE)
.into(holder.thumbnail, new Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError(Exception e) {
mPicasso.load(courseList.get(position).getThumbnailURL())
.error(R.drawable.ofklogo)
.into(holder.thumbnail, new Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError(Exception e) {
}
});
}
});
}
#Override
public int getItemCount() {
return courseList.size();
}
public static class CourseListViewHolder extends RecyclerView.ViewHolder {
ImageView thumbnail;
TextView title;
public CourseListViewHolder(#NonNull View itemView, final OnItemClickListener listener) {
super(itemView);
title = itemView.findViewById(R.id.courseTitle);
thumbnail = itemView.findViewById(R.id.courseThumbNailImageView);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int position = getAdapterPosition();
if (listener != null) {
if (position != RecyclerView.NO_POSITION) {
listener.onItemClick(position, view);
}
}
}
});
}
}
#Override
public int getItemViewType(int position) {
if (mSender.equals("home_page")) {
return HOME_PAGE;
} else if (mSender.equals("displayCourse")) {
return DISPLAY_COURSE;
}
return -1;
}
}
View pager adapter
public class VideoSliderAdapter extends PagerAdapter {
private boolean doNotifyDataSetChangedOnce = false;
private static final String TAG = "VideoSliderAdapter";
private YouTubePlayerView youTubePlayerView;
private View gradientView;
private ImageView thumbNail;
private LinearLayout layout;
private Picasso picasso;
private List<Video> videoList;
private Context mContext;
private Lifecycle mLifeCycle;
public VideoSliderAdapter(List<Video> videoList, Context context, Lifecycle lifecycle) {
this.videoList = videoList;
this.mContext = context;
this.mLifeCycle = lifecycle;
doNotifyDataSetChangedOnce = true;
picasso = Picasso.get();
}
#Override
public int getCount() {
if (doNotifyDataSetChangedOnce) {
doNotifyDataSetChangedOnce = false;
notifyDataSetChanged();
}
return videoList.size();
}
#Override
public int getItemPosition(#NonNull Object object) {
return POSITION_NONE;
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return (view == (CardView) object);
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.video_paly_layout, container, false);
TextView title = view.findViewById(R.id.videoTitle);
title.setText(videoList.get(position).getVideoTitle());
gradientView = view.findViewById(R.id.gradientView);
thumbNail = view.findViewById(R.id.videoThumbNail);
picasso.load(videoList.get(position).getVideoThumbNail())
.networkPolicy(NetworkPolicy.OFFLINE)
.into(thumbNail, new Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError(Exception e) {
picasso.load(videoList.get(position).getVideoThumbNail())
.error(R.drawable.ofklogo)
.into(thumbNail, new Callback() {
#Override
public void onSuccess() {
}
#Override
public void onError(Exception e) {
}
});
}
});
layout = view.findViewById(R.id.videoPlayLayout);
youTubePlayerView = view.findViewById(R.id.youtube_player_view);
mLifeCycle.addObserver(youTubePlayerView);
new AddListener(youTubePlayerView, position).execute();
container.addView(view);
return view;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
container.removeView((CardView) object);
}
Recycler view holder layout
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="150dp"
android:layout_height="200dp"
android:layout_marginStart="8dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
android:clickable="true"
android:focusable="true"
android:foreground="?android:attr/selectableItemBackground"
app:cardCornerRadius="8dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/courseThumbNailImageView"
android:layout_width="match_parent"
android:layout_height="130dp"
android:layout_alignParentTop="true"
android:scaleType="fitXY"
android:src="#drawable/art_thumb" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#id/courseThumbNailImageView">
<TextView
android:id="#+id/courseTitle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:maxLines="2"
android:text="Course title"
android:textAlignment="center"
android:textColor="#android:color/black"
android:textStyle="bold" />
</RelativeLayout>
</RelativeLayout>
</androidx.cardview.widget.CardView>
view pager layout
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView 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="200dp"
app:cardCornerRadius="8dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<com.pierfrancescosoffritti.androidyoutubeplayer.core.player.views.YouTubePlayerView
android:id="#+id/youtube_player_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:autoPlay="false" />
<ImageView
android:id="#+id/videoThumbNail"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scaleType="fitXY" />
<View
android:id="#+id/gradientView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/gradient_drawable" />
<LinearLayout
android:id="#+id/videoPlayLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:background="?attr/selectableItemBackground"
android:clickable="true"
android:focusable="true"
android:gravity="center_vertical"
android:orientation="horizontal"
android:padding="16dp">
<ImageView
android:layout_width="48dp"
android:layout_height="48dp"
android:padding="8dp"
android:src="#drawable/play_button" />
<TextView
android:id="#+id/videoTitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ellipsize="end"
android:maxLines="2"
android:text="Course title"
android:textColor="#android:color/white"
android:textStyle="bold" />
</LinearLayout>
</RelativeLayout>
</androidx.cardview.widget.CardView>
When loading image using Picasso use: setIndicatorsEnabled(false)
picasso.load(videoList.get(position).getVideoThumbNail())
.networkPolicy(NetworkPolicy.OFFLINE)
.setIndicatorsEnabled(false)
.into(...);
The colors indicate this:
Green: Image is fetched from memory
Blue: Image is fetched from disk
Red: Image is fetched from network

Center ViewGroup views with Android-DraggableGridViewPager

I want to thanks zzhouj first of all, but I'm trying to use his Android-DraggableGridViewPager with some errors. this is his class:
Android-DraggableGridViewPager RAW
This is my layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/gridview_layout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="100">
<TextClock
android:gravity="center"
android:textColor="#color/colorBlack"
android:id="#+id/text_clock"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="15"
android:fontFamily="sans-serif-black"
android:text="20:15"
android:textSize="50sp"
android:textStyle="bold" />
<TextView
android:gravity="center"
android:id="#+id/text_date"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="10"
android:fontFamily="sans-serif-thin"
android:text="09/09/09"
android:textColor="#color/colorBlack"
android:textSize="20sp" />
<com.kangel.hybridlauncher.adapters.AppDraggableGridViewPager
android:foregroundGravity="center"
android:id="#+id/draggable_grid_view_pager"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_gravity="center"
android:layout_weight="75"
android:background="#color/colorAccent"
android:gravity="center" />
</LinearLayout>
I'm using it to create a simple gridview with draggable layout in, but if I reduce size of that ViewGroup, the element wont stay in center, because elements go on the left.
Do you have any ideas? Thanks in advance!
EDIT
public class AppArrayAdapter extends ArrayAdapter<AppObject> {
private Context context;
public AppArrayAdapter(#NonNull Context context, int resource) {
super(context, resource);
this.context = context;
}
#Override
public long getItemId(int position) {
return position;
}
#NonNull
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View v;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.gridview_app_layout, parent, false);
} else {
v = convertView;
}
LinearLayout layout = v.findViewById(R.id.single_item_core);
ImageView icon = layout.findViewById(R.id.app_layout);
TextView label = layout.findViewById(R.id.app_label);
final AppObject appObject = this.getItem(position);
icon.setImageDrawable(appObject.getIcon());
label.setText(appObject.getName());
return v;
}
#Override
public void add(#Nullable AppObject object) {
super.add(object);
notifyDataSetChanged();
}
#Override
public void addAll(#NonNull Collection<? extends AppObject> collection) {
super.addAll(collection);
notifyDataSetChanged();
}
#Override
public void addAll(AppObject... items) {
super.addAll(items);
notifyDataSetChanged();
}
#Override
public void insert(#Nullable AppObject object, int index) {
super.insert(object, index);
notifyDataSetChanged();
}
#Override
public void remove(#Nullable AppObject object) {
super.remove(object);
notifyDataSetChanged();
}
#Override
public void clear() {
super.clear();
notifyDataSetChanged();
}
}
EDIT
I set adapter in MainActivity:
DraggableGridViewPager mDraggableGridViewPager = mViewAppsScroll.findViewById(R.id.draggable_grid_view_pager);
mAppAdapter = new AppArrayAdapter(this, 0);
mAppAdapter.addAll(getList());
mDraggableGridViewPager.setAdapter(mAppAdapter);

Listview custom adapter cant select an item

I tried all the solution that i found here in the stackoverflow but it seems like none of them work.
Here is my main activity:
public class MerchantLocatorActivity extends AppCompatActivity implements OnMapReadyCallback {
public void init(){
merchantLocatorResponseObject = new MerchantLocatorResponse();
merchantLocatorResponseObject.setTitle("Spherical");
merchantLocatorResponseObject.setAddress("8007 Pioneer St, Kapitolyo, Mandaluyong, 1550 Metro Manila");
merchantLocatorResponseObject.setLatitude( 14.573249);
merchantLocatorResponseObject.setLongitude(121.057022);
merchantLocatorObjectArray.add(merchantLocatorResponseObject);
merchantLocatorResponseObject = new MerchantLocatorResponse();
merchantLocatorResponseObject.setTitle("Globe");
merchantLocatorResponseObject.setAddress("SCT, 584 Shaw Blvd, Mandaluyong, 1552 Metro Manila");
merchantLocatorResponseObject.setLatitude(14.585095);
merchantLocatorResponseObject.setLongitude(121.048893);
merchantLocatorObjectArray.add(merchantLocatorResponseObject);
merchantLocatorResponseObject = new MerchantLocatorResponse();
merchantLocatorResponseObject.setTitle("Sparndium");
merchantLocatorResponseObject.setAddress("Xavier, San Juan, 1502 Metro Manila");
merchantLocatorResponseObject.setLatitude(14.601918);
merchantLocatorResponseObject.setLongitude(121.042169);
merchantLocatorObjectArray.add(merchantLocatorResponseObject);
addMarker();
}
#OnClick(R.id.fab)
public void showAccToDialog() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
View alertView = LayoutInflater.from(this).inflate(R.layout.dialog_biller, null);
alertDialogBuilder.setView(alertView);
final AlertDialog dialog = alertDialogBuilder.create();
dialog.show();
final ListView listViewBillers = (ListView) dialog.findViewById(R.id.biller_institutions_listview);
if (listViewBillers != null) {
MerchantLocatorAdapter adapter = new MerchantLocatorAdapter(
this, R.layout.merchant_locator_adapter, merchantLocatorObjectArray);
listViewBillers.setAdapter(adapter);
listViewBillers.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
geoLocate(merchantLocatorObjectArray,position);
DebugUtils.log("TESTTESTACTIVITYZXC");
DebugUtils.showToast(MerchantLocatorActivity.this,"HAHAHAH");
dialog.dismiss();
}
});
final EditText mSearchedittext = (EditText) dialog.findViewById(R.id.search_edittext);
mSearchedittext.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
final ArrayList<MerchantLocatorResponse> searchResultObject = new ArrayList<>();
searchResultObject.clear();
for (int hay = 0; hay <= merchantLocatorObjectArray.size() - 1; hay++) {
if ( merchantLocatorObjectArray.get(hay).getTitle().toLowerCase().contains(charSequence)) {
searchResultObject.add( merchantLocatorObjectArray.get(hay));
}
}
MerchantLocatorAdapter adapter = new MerchantLocatorAdapter(
MerchantLocatorActivity.this, R.layout.merchant_locator_adapter, searchResultObject);
listViewBillers.setAdapter(adapter);
listViewBillers.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View view, int position, long arg) {
geoLocate(searchResultObject,position);
dialog.dismiss();
}
});
}
#Override
public void afterTextChanged(Editable editable) {
}
});
}
}
}
i remove some part of the code because i think it's un necessary to include but let me know if there's some part that i need some clarification.
currently in my main activity, i'm calling a dialog that contains a listview and in my listview i have items.
My problem is i can't select any of my items even thought i have my setOnitemclick listener.
here is my adapter:
public class MerchantLocatorAdapter extends BaseAdapter {
private int resourceLayout;
private Context mContext;
ArrayList<MerchantLocatorResponse> merchantLocatorarray = new ArrayList<>();
public MerchantLocatorAdapter(Context context, int resource, ArrayList<MerchantLocatorResponse> merchantLocatorResponsesobjectArray) {
this.resourceLayout = resource;
this.mContext = context;
this.merchantLocatorarray = merchantLocatorResponsesobjectArray;
}
#Override
public int getCount() {
return merchantLocatorarray.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(mContext.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(resourceLayout, parent, false);
}
TextView tt1 = (TextView) convertView.findViewById(R.id.field_name_textview);
TextView tt2 = (TextView) convertView.findViewById(R.id.field_value_textview);
ImageButton direction = (ImageButton) convertView.findViewById(R.id.direction);
tt1.setText(merchantLocatorarray.get(position).getTitle());
tt2.setText(merchantLocatorarray.get(position).getAddress());
return convertView;
}
}
here is my layout for my adapter:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.CardView
android:id="#+id/card_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center"
android:layout_margin="8dp"
android:elevation="3dp">
<LinearLayout
android:id="#+id/card_overflow"
android:focusable="true"
android:clickable="true"
android:background="#fff"
android:paddingLeft="16dp"
android:paddingRight="0dp"
android:paddingTop="10dp"
android:paddingBottom="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:weightSum="1">
<TextView
android:id="#+id/field_name_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="5dp"
android:layout_toLeftOf="#+id/branch_btns"
android:layout_alignParentLeft="true"
android:textSize="17sp"
android:textStyle="bold"
android:textColor="#color/edittext_text"
android:text="test"/>
<LinearLayout
android:id="#+id/branch_btns"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:orientation="horizontal"
>
<ImageButton
android:id="#+id/direction"
android:layout_width="50sp"
android:layout_height="wrap_content"
android:src="#drawable/ic_direction"
android:scaleType="fitCenter"
android:background="#color/translucent_clear_bg"
/>
<ImageButton
android:id="#+id/btn_branch_phone"
android:layout_width="50sp"
android:layout_height="wrap_content"
android:src="#drawable/ic_call_phone"
android:scaleType="fitCenter"
android:background="#color/translucent_clear_bg"
/>
</LinearLayout>
</RelativeLayout>
<View
android:id="#+id/seperator"
android:layout_width="match_parent"
android:layout_height="2dp"
android:layout_marginBottom="5dp"
android:background="#android:color/darker_gray"
android:visibility="gone"
android:layout_marginTop="2dp"/>
<TextView
android:id="#+id/field_value_textview"
android:textSize="14sp"
android:textColor="#color/edittext_tint"
android:layout_marginTop="5dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="test"/>
</LinearLayout>
</android.support.v7.widget.CardView>
</LinearLayout>
i tried every solution that i found here in stackoverflow, and yet i can't still click my item. so please don't mark this as a duplicate.
if there's any part of the code that need clarification, please leave a comment and i'll answer as soon as possible. thanks.
Try to use Observable in you custom adapter:
// Define
private final PublishSubject<MerchantLocatorResponse> onItemClick = PublishSubject.create();
// Create the observable method
public Observable<ConversationMessage> getObservable(){
return onItemClick;
}
// Set the onClickListener into getView()
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onItemClick.onNext(merchantLocatorarray.get(position));
}
});
Then, in your main activity listen to it and handle the click:
#OnClick(R.id.fab)
public void showAccToDialog() {
// bla bla bla
listViewBillers.setAdapter(adapter);
listViewBillers.getObservable().subscribe(geoLocate);
// bla bla bla
}
Consumer<MerchantLocatorResponse> geoLocate = new Consumer<MerchantLocatorResponse>() {
#Override
public void accept(MerchantLocatorResponse mlr) {
// Code after click event
}
};
Add those library in your gradle:
implementation "io.reactivex.rxjava2:rxjava:2.1.5"
implementation "io.reactivex.rxjava2:rxandroid:2.0.1"
Add convertView.setOnclickListener() in your code. Try below code in your adapter
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(mContext.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(resourceLayout, parent, false);
}
TextView tt1 = (TextView) convertView.findViewById(R.id.field_name_textview);
TextView tt2 = (TextView) convertView.findViewById(R.id.field_value_textview);
ImageButton direction = (ImageButton) convertView.findViewById(R.id.direction);
tt1.setText(merchantLocatorarray.get(position).getTitle());
tt2.setText(merchantLocatorarray.get(position).getAddress());
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context, String.valueOf(position), Toast.LENGTH_SHORT).show();
}
});
return convertView;
} }

Custom CursorAdapter to click inside list-item-view

I've successfully managed to extend a CursorAdapter and change the bindView- and newView-methods to be able to have clickable buttons inside my list. The button (which actually is a clickable ImageView) uses a selector as a backgroundresource, and everything works fine except that when I click the list-item-view, the selector of the button/imageview is activated and hence it appears as if I clicked the button/imageview even though I didn't. The method inside the onclicklistener that's bound to the button/imageview though, is not activated when clicking the list-item-view, so that works properly, it's only the selector. Here is my CustomCursorAdapter:
public class CustomCursorAdapter extends CursorAdapter {
Context context;
LayoutInflater inflater;
AlertDialog.Builder builder;
public CustomCursorAdapter(Context context, Cursor cursor, int flags) {
super(context, cursor, flags);
this.context = context;
inflater = LayoutInflater.from(context);
}
#Override
public void bindView(View view, Context c, Cursor cursor){
ViewHolder holder = (ViewHolder) view.getTag();
final Context context = c;
final String name = cursor.getString(cursor.getColumnIndex("name"));
final String number = cursor.getString(cursor.getColumnIndex("number"));
final String mail = cursor.getString(cursor.getColumnIndex("mail"));
holder.getTvName().setText(name);
holder.getTvNumber().setText(number);
holder.getTvMail().setText(mail);
int row_id = cursor.getInt(cursor.getColumnIndex("_id"));
holder.getCallButton().setTag(row_id);
holder.getCallButton().setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
builder = new AlertDialog.Builder(context);
builder.setMessage("Call " + name + "?")
.setPositiveButton("Call", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
String uri = "tel:" + nummer.trim();
Intent intent = new Intent(Intent.ACTION_CALL);
intent.setData(Uri.parse(uri));
context.startActivity(intent);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
builder.create().show();
}
});
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View convertView = inflater.inflate(R.layout.contact_list_row, parent, false);
ViewHolder holder = new ViewHolder();
holder.setCallButton((ImageView) convertView.findViewById(R.id.bCall));
holder.setTvName((TextView) convertView.findViewById(R.id.tvName));
holder.setTvNumber((TextView) convertView.findViewById(R.id.tvNumber));
holder.setTvMail((TextView) convertView.findViewById(R.id.tvMail));
convertView.setTag(holder);
return convertView;
}
public static class ViewHolder {
private TextView tvName, tvNumber, tvMail;
private ImageView bCall;
public ImageView getCallButton() {
return bCall;
}
public void setCallButton(ImageView bCall) {
this.bCall = bCall;
}
public TextView getTvName() {
return tvName;
}
public void setTvName(TextView tvName) {
this.tvName = tvName;
}
public TextView getTvNumber() {
return tvNumber;
}
public void setTvNumber(TextView tvNumber) {
this.tvNumber = tvNumber;
}
public TextView getTvMail() {
return tvMail;
}
public void setTvMail(TextView tvMail) {
this.tvMail = tvMail;
}
}
}
This is the listView-XML:
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:cacheColorHint="#android:color/transparent"
android:listSelector="#android:color/transparent" />
And the contact_list_row.XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#drawable/list_background"
android:orientation="horizontal" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/tvName"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/tvNumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/tvMail"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
<ImageView
android:id="#+id/bCall"
android:background="#drawable/button"
android:clickable="true"
android:src="#drawable/ic_clean_phone" />
Selector:
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:state_pressed="true" android:drawable="#drawable/h_main_button_background_pressed"></item>
<item android:drawable="#drawable/h_main_button_background"></item>
</selector>
If you find any other errors or unnecessary code, I'm very thankful for that too!

Categories

Resources