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
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 am trying to implement a simple listView with onClick functionality. On clicking the item in the listView, I want to show the name of the item in a 'toast message, but I am unable to do that. I have used the method suggested in this link and link but couldn't get the desired result. I have added my code below :
MainActivity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rowItem = new AppList();
final ListView userInstalledApps = (ListView)findViewById(R.id.appListView);
List<AppList> installedApps = getInstalledApps();
CustomAppAdapter installedAppAdapter = new CustomAppAdapter(MainActivity.this, installedApps);
userInstalledApps.setAdapter(installedAppAdapter);
userInstalledApps.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
TextView appName = (TextView)adapterView.findViewById(R.id.list_app_name);
Toast.makeText(getApplicationContext(),
"Clicked "+ adapterView.getItemAtPosition(i),Toast.LENGTH_LONG).show();
}
});
}
CustomAppAdapter.java
public class CustomAppAdapter extends BaseAdapter {
private LayoutInflater layoutInflater;
private List<AppList> listStorage;
Context context;
public CustomAppAdapter(Context context, List<AppList> listStorage) {
layoutInflater =(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.listStorage = listStorage;
}
#Override
public int getCount() {
return listStorage.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder listViewHolder;
if(convertView == null){
listViewHolder = new ViewHolder();
convertView = layoutInflater.inflate(R.layout.installed_app_list, parent, false);
listViewHolder.textInListView = (TextView)convertView.findViewById(R.id.list_app_name);
listViewHolder.imageInListView = (ImageView)convertView.findViewById(R.id.app_icon);
convertView.setTag(listViewHolder);
}else{
listViewHolder = (ViewHolder)convertView.getTag();
}
listViewHolder.textInListView.setText(listStorage.get(position).getName());
listViewHolder.imageInListView.setImageDrawable(listStorage.get(position).getIcon());
return convertView;
}
static class ViewHolder{
TextView textInListView;
ImageView imageInListView;
}
}
Below is the screenshot of the listView :
On trying this method:
Toast.makeText(getApplicationContext(),
"Clicked "+ adapterView.getItemAtPosition(i),Toast.LENGTH_LONG).show();
Suppose I clicked on the 2nd item in the listView so I get a toast message as Clicked 2. But I want that it shows me Clicked PhonePe
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rowItem = new AppList();
final ListView userInstalledApps = (ListView)findViewById(R.id.appListView);
List<AppList> installedApps = getInstalledApps();
CustomAppAdapter installedAppAdapter = new CustomAppAdapter(MainActivity.this, installedApps);
userInstalledApps.setAdapter(installedAppAdapter);
userInstalledApps.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
TextView appName = (TextView)adapterView.findViewById(R.id.list_app_name);
Toast.makeText(getApplicationContext(),
"Clicked "+ installedApps.get(i).getName(),Toast.LENGTH_LONG).show();
}
});
}
Try this.
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);
}
}
I am using a recycler view and items are added to it programatically on user's requirement. When I install the application on my device, the programmatically added items are shown up. But when I kill the app and open it again, the items added programmatically are not showing up. I have maintained an arraylist of items which initially contains 3 items. Any further additions to the llistt are not retained once the app is killed.
Any help is appreciated. Please help!
I am attaching my adapter class and fragment class containing the recycler view.
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.MyViewHolder> {
List<MyItem> items;
private LayoutInflater inflater;
private Context context;
public MyAdapter(Context context, List<MyItem> items){
this.items = items;
this.context = context;
inflater = LayoutInflater.from(context);
}
#Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = inflater.inflate(R.layout.item_my_list, parent, false);
MyViewHolder myHolder= new MyViewHolder(view);
return myHolder;
}
#Override
public void onBindViewHolder(MyAdapter.MyViewHolder holder, int position) {
MyItem item = items.get(position);
holder.name.setText(item.get_Name());
holder.number.setText(item.get_Number());
}
#Override
public int getItemCount() {
return items.size();
}
public void delete(int position) {
items.remove(position);
notifyItemRemoved(position);
}
public void add(MyItem item, int position){
items.add(position, item);
notifyItemInserted(position);
notifyItemRangeChanged(0, getItemCount());
}
class MyViewHolder extends RecyclerView.ViewHolder{
TextView number, name;
public MyViewHolder(View itemView){
super(itemView);
number =(TextView) itemView.findViewById(R.id.number);
name = (TextView) itemView.findViewById(R.id.name);
}
}
}
nd here's my fragment class:
public class RecyclerViewFragment extends Fragment {
RecyclerView myRecyclerView;
RecyclerView.Adapter adapter;
TextView addItem;
TextView nameText, numberText;
private static List<MyItem> items;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_recycler_view, container, false);
myRecyclerView = (RecyclerView) view.findViewById(R.id.my_list);
adapter = new MyAdapter(getActivity(), getData());
Log.i("DATA ITEMS", getData().get(0).get_contactName());
Log.i("DATA ITEMS", getData().get(0).get_contactName());
Log.i("DATA ITEMS", getData().get(0).get_contactName());
addItem = (TextView) view.findViewById(R.id.add_new_item);
myRecyclerView.setAdapter(adapter);
myRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
myRecyclerView.addOnItemTouchListener(new RecyclerViewTouchListener(getActivity(), myRecyclerView, new ClickListener() {
#Override
public void onClick(View view, int position) {
Log.i("MY INFO", "item of recycler view clicked" + position);
}
#Override
public void onLongClick(View view, int position) {
}
}));
addItem.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addNewItem();
}
});
return view;
}
public static List<MyItem> getData(){
items = new ArrayList<>();
items.add(new MyItem("7341973", "xyzabc"));
items.add(new MyItem("86218", "qwerty"));
items.add(new MyItem("178581", "bnmlkjh"));
return items;
}
public void addNewItem(){
LayoutInflater li = LayoutInflater.from(this.getActivity());
View view = li.inflate(R.layout.dialog_add_item, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this.getActivity());
alertDialogBuilder.setView(view);
nameText = (TextView) view.findViewById(R.id.new_name);
numberText = (TextView) view.findViewById(R.id.new_number);
alertDialogBuilder
.setCancelable(false)
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
})
.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if(numberText.getText() != null && nameText.getText() != null){
MyItem item = new MyItem(numberText.getText().toString(), nameText.getText().toString());
((MyAdapter) adapter).add(item, 0);
}
else
Toast.makeText(getActivity(), "Add name and number", Toast.LENGTH_SHORT).show();
}
});
AlertDialog dialog = alertDialogBuilder.create();
dialog.show();
}
public interface ClickListener{
void onClick(View view, int position);
void onLongClick(View view, int position);
}
static class RecyclerViewTouchListener implements RecyclerView.OnItemTouchListener{
private GestureDetector detector;
private ClickListener listener;
public RecyclerViewTouchListener (Context context, final RecyclerView recyclerView, final ClickListener clickListener){
this.listener = clickListener;
detector = new GestureDetector(context, new GestureDetector.SimpleOnGestureListener(){
#Override
public boolean onSingleTapUp(MotionEvent e) {
return true;
}
#Override
public void onLongPress(MotionEvent e) {
View child = recyclerView.findChildViewUnder(e.getX(), e.getY());
if (child != null && clickListener != null) {
clickListener.onLongClick(child, recyclerView.getChildAdapterPosition(child));
}
}
});
}
#Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
View child = rv.findChildViewUnder(e.getX(), e.getY());
if (child != null && listener != null && detector.onTouchEvent(e)) {
listener.onClick(child, rv.getChildAdapterPosition(child));
}
return false;
}
#Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
#Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
}
}
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;
}
}