I have a GridViewActivity, GridViewAdapter, FullScreenActivity and FullScreenImageAdapter. When I click Image from GridView, go to FullScreenActivity and it doesn't show nothing. I also test from Drawable imgDisplay.setImageResource(R.drawable.a); It doesn't happen. What wrong? How can I solve? Please!
In GridViewAdapter; Image Click Listener,
private class OnImageClickListener implements View.OnClickListener {
int _postion;
public OnImageClickListener(int position) {
this._postion = position;
}
#Override
public void onClick(View v) {
Intent i = new Intent(_activity, FullScreenActivity.class);
i.putExtra("position", _postion);
_activity.startActivity(i);
}
}
In FullScreenActivity; get position from GridView, and then I create new FullScreenImageAdapter
List<Item> mItems = new ArrayList<>();
int position = getIntent().getIntExtra("position", 0);
Log.i("Result", String.valueOf(position)); // return 0,1,2,3.. etc
adapter = new FullScreenImageAdapter(FullScreenActivity.this, mItems);
viewPager.setAdapter(adapter);
In FullScreenImageAdapter;
public class FullScreenImageAdapter extends PagerAdapter {
List<Item> mItems = new ArrayList<>();
Activity _activity;
LayoutInflater inflater;
public FullScreenImageAdapter(Activity activity, List<Item> mItems) {
this._activity = activity;
this.mItems = mItems;
}
#Override
public int getCount() {
return mItems.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((RelativeLayout) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
ImageView imgDisplay;
inflater = (LayoutInflater) _activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View viewLayout = inflater.inflate(R.layout.layout_fullscreen_image, container, false);
imgDisplay = (ImageView) viewLayout.findViewById(R.id.imgDisplay);
imgDisplay.setImageResource(R.drawable.a); // want to show from mItems List
((ViewPager) container).addView(viewLayout);
return viewLayout;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((RelativeLayout) object);
}
}
Related
I would like someone to click on an item in my ListView and then my new activity would start and the text of the item they clicked on should be set as the text of the TextView in my new activity. Currently with the following code, my TextView result is:
'com.example.draft.AnimalNames#31571cf'
Here is what I have in MainActivity.java:
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String clickedName = (list.getItemAtPosition(position).toString());
Intent intent = new Intent(MainActivity.this, Profile.class);
intent.putExtra("clickedName", clickedName);
startActivity(intent);
System.out.println(clickedName);
}
});
And in my new activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.profile_layout);
Intent intent = getIntent();
String clickedName = intent.getStringExtra("clickedName");
animalName = findViewById(R.id.textView);
animalName.setText(clickedName);
}
And in my AnimalNames.java file:
public class AnimalNames {
private String animalName;
public AnimalNames(String animalName) {
this.animalName = animalName;
}
public String getanimalName() {
return this.animalName;
}
}
I don't think it's relevant to my question but here is my ListViewAdapter.java file:
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context mContext;
LayoutInflater inflater;
private List<AnimalNames> animalNamesList; // Declare a null variable
private ArrayList<AnimalNames> arraylist; // Declare a null array
public ListViewAdapter(Context context, List<AnimalNames> animalNamesList) {
mContext = context;
this.animalNamesList = animalNamesList;
inflater = LayoutInflater.from(mContext);
this.arraylist = new ArrayList<AnimalNames>();
this.arraylist.addAll(animalNamesList);
}
public class ViewHolder {
TextView name;
}
#Override
public int getCount() {
return animalNamesList.size();
}
#Override
public AnimalNames getItem(int position) {
return animalNamesList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.list_view_items, null); // Locate the TextViews in list_view_items.xml
holder.name = (TextView) view.findViewById(R.id.name);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// Set the results into TextViews
holder.name.setText(animalNamesList.get(position).getanimalName());
return view;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
animalNamesList.clear();
if (charText.length() == 0) {
animalNamesList.addAll(arraylist);
} else {
for (AnimalNames wp : arraylist) {
if (wp.getanimalName().toLowerCase(Locale.getDefault()).contains(charText)) {
animalNamesList.add(wp);
}
}
}
notifyDataSetChanged();
}
}
String clickedName = (list.getItemAtPosition(position).toString());
By calling toString() method, it will give you the object reference, which is what you get in the TextView.
According to your code, if you wish to see the Animal name, you should do (and fix the method name to getAnimalName):
String clickedName = ((AnimalNames)list.getItemAtPosition(position)).getanimalName();
getItemAtPosition() returns an Object, so you need to cast it to the correct class.
I have created a RecyclerView and added cards in fragment.I want to open different activities by clicking on different cards in CardView.But I am only able to open the same activity for all the cards.I searched different answers in StackOverFlow.But I couldn't.
could you tell me how to solve this issue...? If you can give full code,I'm happy.
Here are my codes...
PDFFragment.java
public class PDFFragment extends Fragment {
View v;
List<Pdf> listBook;
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
v= inflater.inflate(R.layout.fragment_pdf,container,false);
listBook = new ArrayList<>();
listBook.add(new Pdf("1-pdf name",R.drawable.pdf1image));
listBook.add(new Pdf("2-pdf name",R.drawable.pdf2image));
listBook.add(new Pdf("3-pdf name",R.drawable.pdf3image));
listBook.add(new Pdf("4-pdf name",R.drawable.pdf4image);
listBook.add(new Pdf("5-pdf name",R.drawable.pdf5image));
listBook.add(new Pdf("6-pdf name",R.drawable.pdf6image));
listBook.add(new Pdf("7-pdf name",R.drawable.pdf7image));
RecyclerView myTV= (RecyclerView) v.findViewById(R.id.recyclerview_id);
RecyclerViewAdapterPDF myAdapter = new RecyclerViewAdapterPDF(getActivity(),listBook);
//Part 1 -Start Changing number of columns
myTV.setLayoutManager(new GridLayoutManager(getActivity(),calculateNoOfColumns(getActivity())));
//Part 1 -End Changing number of columns
myTV.setAdapter(myAdapter);
return v;
}
//Part 2 -Start Changing number of columns
public int calculateNoOfColumns(Context context) {
DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
float dpWidth = displayMetrics.widthPixels / displayMetrics.density;
int noOfColumns = (int) (dpWidth / 120);
return noOfColumns;
}
//Part 2 -End Changing number of columns
}
RecyclerViewAdapterPDF.java
public class RecyclerViewAdapterPDF extends RecyclerView.Adapter<RecyclerViewAdapterPDF.MyViewHolder> {
private Context mContext;
private List<Pdf> mData;
public RecyclerViewAdapterPDF(Context mContext, List<Pdf> mData) {
this.mContext = mContext;
this.mData = mData;
}
#Override
public MyViewHolder onCreateViewHolder( ViewGroup parent, int viewType) {
View view;
LayoutInflater mInflater = LayoutInflater.from(mContext);
view = mInflater.inflate(R.layout.cardview_item_pdf,parent,false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder( MyViewHolder holder, int position) {
holder.tv_book_title.setText(mData.get(position).getTitle());
holder.img_book_thumbnail.setImageResource(mData.get(position).getPhoto());
}
#Override
public int getItemCount() {
return mData.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder{
TextView tv_book_title;
ImageView img_book_thumbnail;
public MyViewHolder(View itemView) {
super(itemView);
tv_book_title = (TextView) itemView.findViewById(R.id.book_title_id);
img_book_thumbnail = (ImageView) itemView.findViewById(R.id.book_image_id);
}
}
}
ViewPagerAdapter.java
public class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> fragmentList = new ArrayList<>();
private final List<String> FragmentListTitles = new ArrayList<>();
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
#Override
public int getCount() {
return FragmentListTitles.size();
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return FragmentListTitles.get(position);
}
public void AddFragment(Fragment fragment,String Title){
fragmentList.add(fragment);
FragmentListTitles.add(Title);
}
}
You need a reference to your card on the view holder:
public static class MyViewHolder extends RecyclerView.ViewHolder{
TextView tv_book_title;
ImageView img_book_thumbnail;
CardView cardview;
public MyViewHolder(View itemView) {
super(itemView);
tv_book_title = (TextView) itemView.findViewById(R.id.book_title_id);
img_book_thumbnail = (ImageView) itemView.findViewById(R.id.book_image_id);
cardview = itemView.findViewById(R.id.yourCardId);
}
}
And on the onBindViewHolder() you set a click listener responsible for opening the activity:
#Override
public void onBindViewHolder( MyViewHolder holder, int position) {
holder.tv_book_title.setText(mData.get(position).getTitle());
holder.img_book_thumbnail.setImageResource(mData.get(position).getPhoto());
holder.cardView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent;
switch (position) {
case 0:
intent = new Intent(mContext, pdfone.class);
mContext.startActivity(intent);
break;
case 1:
intent = new Intent(mContext, pdftwo.class);
mContext.startActivity(intent);
break;
...
//do the same for every card possible
}
}
}
Use reflection like this
So in your case, something like:
String activityToStart = "com.pkg.pdf"+position;
try {
Class<?> c = Class.forName(activityToStart);
Intent intent = new Intent(this, c);
startActivity(intent);
} catch (ClassNotFoundException e) {
// print exception
}
Put it in adapter when page is to be changed.
I have alter dialog that contains listview with custom adapter populated by some items. Each item has a name and id.
This is item holder:
public class TOperaterHolder {
private String NazivOperatera;
private String IDOperater;
public TOperaterHolder(String nazivOperater, String idOperater) {
this.NazivOperatera = nazivOperater;
this.IDOperater = idOperater;
}
public String getNazivOperatera() {
return NazivOperatera;
}
public void setNazivOperatera(String nazivOperatera) {
NazivOperatera = nazivOperatera;
}
public String getIDOperater() {
return IDOperater;
}
public void setIDOperater(String IDOperater) {
this.IDOperater = IDOperater;
}
}
and this is the custom adapter:
public class CustomAdapterTOperateri extends BaseAdapter {
ArrayList<TOperaterHolder> mData;
Context mContext;
LayoutInflater inflater;
public CustomAdapterTOperateri(ArrayList<TOperaterHolder> data, Context context) {
mData = data;
mContext = context;
inflater = LayoutInflater.from(mContext);
}
public class ViewHolder {
TextView txtNazivTOperater;
}
#Override
public int getCount() {
return mData.size();
}
#Override
public TOperaterHolder getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
if (view == null) {
LayoutInflater mInflater = (LayoutInflater) mContext
.getSystemService(mContext.LAYOUT_INFLATER_SERVICE);
view = mInflater.inflate(R.layout.inflate_red, null);
}
TextView tvTitle = (TextView) view.findViewById(R.id.txtNazivTOperater);
View v = (View) view.findViewById(R.id.listViewTOperater);
tvTitle.setText(mData.get(position).getNazivOperatera());
return view;
}
}
This part is placed in activity where I have method to show alter dialog with listview:
private void AlertListItems()
{
AlertDialog.Builder dialog = new AlertDialog.Builder(IzborRazduzivanje.this);
dialog.setTitle("List Title");
View customView = LayoutInflater.from(IzborRazduzivanje.this).inflate(
R.layout.inflate, null, false);
ListView listView = (ListView) customView.findViewById(R.id.listViewTOperater);
ArrayList<TOperaterHolder> itemList = new ArrayList<TOperaterHolder>();
itemList.add(new TOperaterHolder("J", "1"));
itemList.add(new TOperaterHolder("B", "2"));
itemList.add(new TOperaterHolder("C", "3"));
CustomAdapterTOperateri mAdapter = new CustomAdapterTOperateri(itemList, IzborRazduzivanje.this);
listView.setAdapter(mAdapter);
listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
dialog.setView(customView);
dialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
dialog.show();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
TOperaterHolder item = (TOperaterHolder)adapterView.getItemAtPosition(i);
System.out.println("Selected item: " + item.getIDOperater());
}
});
}
When the alert dialog is open I see all three items but when I click on any of them I get an error like
java.lang.NullPointerException: TOperaterHolder.getIDOperater()' on a null object reference
What could be wrong here?
Use
TOperaterHolder item = itemList.get(i);
instead of
TOperaterHolder item = (TOperaterHolder)adapterView.getItemAtPosition(i);
in the onItemClickListener
I have a list in which i can assigned the values statically.
private List<ListData> mDataList = Arrays.asList(
new ListData("Arun"),
new ListData("Jega"),
new ListData("Kabilan"),
new ListData("Karthick"),
new ListData("Joushva"),
new ListData("Niranjana"),
new ListData("Paramesh"),
new ListData("Prabha"),new ListData("Test1"),new ListData("Test2") );
The problem is now i got a scenario where i should get these value dynamically from web apim and i have to set it to the List variable mDataList.
Please help me to clear this. Thanks in advance.
Here is my complete code.
public class ReportFragment extends Fragment {
View ParentView;
private static final int HIGHLIGHT_COLOR = 0x999be6ff;
// list of data items
private List<ListData> mDataList = Arrays.asList(
new ListData("Arun"),
new ListData("Jega"),
new ListData("Kabilan"),
new ListData("Karthick"),
new ListData("Joushva"),
new ListData("Niranjana"),
new ListData("Paramesh"),
new ListData("Prabha"),new ListData("Test1"),new ListData("Test2")
);
// declare the color generator and drawable builder
private ColorGenerator mColorGenerator = ColorGenerator.MATERIAL;
private TextDrawable.IBuilder mDrawableBuilder;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ParentView= inflater.inflate(R.layout.report_fragment, container, false);
init();
return ParentView;
}
public void init(){
mDrawableBuilder = TextDrawable.builder()
.round();
// init the list view and its adapter
final ListView listView = (ListView) ParentView.findViewById(R.id.listView1);
listView.setAdapter(new SampleAdapter());
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
}
private class SampleAdapter extends BaseAdapter {
#Override
public int getCount() {
return mDataList.size();
}
#Override
public ListData getItem(int position) {
return mDataList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = View.inflate(getActivity() , R.layout.list_item_layout, null);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
ListData item = getItem(position);
// provide support for selected state
updateCheckedState(holder, item);
holder.imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// when the image is clicked, update the selected state
ListData data = getItem(position);
data.setChecked(!data.isChecked);
updateCheckedState(holder, data);
}
});
holder.textView.setText(item.data);
return convertView;
}
private void updateCheckedState(ViewHolder holder, ListData item) {
if (item.isChecked) {
holder.imageView.setImageDrawable(mDrawableBuilder.build(" ", 0xff616161));
holder.view.setBackgroundColor(HIGHLIGHT_COLOR);
holder.checkIcon.setVisibility(View.VISIBLE);
}
else {
TextDrawable drawable = mDrawableBuilder.build(String.valueOf(item.data.charAt(0)), mColorGenerator.getColor(item.data));
holder.imageView.setImageDrawable(drawable);
holder.view.setBackgroundColor(Color.TRANSPARENT);
holder.checkIcon.setVisibility(View.GONE);
}
}
}
private static class ViewHolder {
private View view;
private ImageView imageView;
private TextView textView;
private ImageView checkIcon;
private ViewHolder(View view) {
this.view = view;
imageView = (ImageView) view.findViewById(R.id.imageView);
textView = (TextView) view.findViewById(R.id.textView);
checkIcon = (ImageView) view.findViewById(R.id.check_icon);
}
}
private static class ListData {
private String data;
private boolean isChecked;
public ListData(String data) {
this.data = data;
}
public void setChecked(boolean isChecked) {
this.isChecked = isChecked;
}
}
}
create a method to add items in your adapter class, this method will add item to
itemlist. this will add items dynamically on your list or grid.
e.g
public void addItem(Item item){
itemList.add(item);
notifydatasetchanged();}
create a adapter class and constructor, in constructor just initialize the item arraylist and create extra method called addItem() this method will add item to your arraylist. after that you just have to call notifyDatasetchanged and your new item will be added.
I've been trying set custom ListView adapter for navigation drawer it derived from BaseAdapter so when I set OnItemClickListener it doesn't work on either ListView.OnItemClickListener and AdapterView.OnItemClickListener.
Googled around but all examples derive from ArrayAdapter since BaseAdapter desired.
Can anyone help me on this?
NavigationDrawer fragment onCreateView
drawerItems = new ArrayList<DrawerItem>();
drawerItems.add(DrawerItem.create(1, getString(R.string.ideas), getDrawable(R.drawable.ic_action_diamond)));
drawerItems.add(DrawerItem.create(2, getString(R.string.categories), getDrawable(R.drawable.ic_action_categories)));
drawerItems.add(DrawerItem.create(3, getString(R.string.priorities), getDrawable(R.drawable.ic_action_priorities)));
mDrawerListAdapter = MenuAdapter.newInstance(getActivity(), drawerItems);
mDrawerListView.setItemsCanFocus(true);
mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d(TAG, String.valueOf(position));
selectItem(position);
}
});
mDrawerListView.setAdapter(mDrawerListAdapter);
mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
My custom adapter
public class MenuAdapter extends BaseAdapter {
private static final String TAG = "AD:MENU";
private final LayoutInflater mLayoutInflater;
private List<DrawerItem> items;
private Context context;
public MenuAdapter(Context ctx, List<DrawerItem> items) {
this.items = items;
this.context = ctx;
this.mLayoutInflater = LayoutInflater.from(ctx);
}
public static MenuAdapter newInstance(Context ctx, List<DrawerItem> items) {
return new MenuAdapter(ctx, items);
}
#Override
public int getCount() {
return items == null ? 0 : items.size();
}
#Override
public Object getItem(int position) {
return items.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View v, ViewGroup parent) {
DrawerItem item = (DrawerItem) getItem(position);
ViewHolder holder;
if (v == null) {
v = mLayoutInflater.inflate(R.layout.drawable_item, parent, false);
holder = new ViewHolder();
if (v != null) {
holder.title = (TextView) v.findViewById(R.id.menu_title);
holder.title.setTag(item.id);
v.setTag(holder);
}
} else {
holder = (ViewHolder) v.getTag();
}
holder.title.setText(item.title);
holder.title.setCompoundDrawablesWithIntrinsicBounds(item.icon, null, null, null);
Log.d(TAG, item.title);
return v;
}
public class ViewHolder {
TextView title;
}
}