A null pointer exception on a textView in android - java

I am working on an app for school where I have to crate a shopping list and when I select one list I should get a new activity with the products on that list. Now my problem is that when I try to get the clicked element in the listView and then put the products on that list in the listview of the new activity I get a null pointer exception on a textview.
This is the textview that gets the exception
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:textSize="20dp"
android:textColor="#236B8E"
android:layout_marginTop="20dp"
android:id="#+id/products_on_list"/>
</LinearLayout>
This is the listView in my new activity:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/shopping_list_details">
</ListView>
</LinearLayout>
Here's the java code for the new activity:
public class DisplayShoppingListDetailsActivity extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//defines the activity layout
setContentView(R.layout.shopping_list_details);
ListView listView = (ListView) findViewById(R.id.listView_shopping_lists);
Intent intent = getIntent();
String name = intent.getStringExtra("list");
ProductsOnListAdapter ad = new ProductsOnListAdapter(this, -1, Service.getService().getProductsOnList(name));
listView.setAdapter(ad);
}
}
this is the fragment where I have the list of shopping lists. Here is where I create the Intent to the new activity:
public class Fragment1 extends Fragment {
public Fragment1() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment1, container, false);
final ListView listView = (ListView) rootView.findViewById(R.id.listView_shopping_lists);
// get data from the table by the ListAdapter
ShoppingListAdapter listAdapter = new ShoppingListAdapter(getActivity(), -1, Service.getService().getShoppingLists());
listView.setAdapter(listAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// selected item
// HERE IS THE PROBLEM
// I have tried to use rootView instead of view
TextView textview = (TextView) view.findViewById(R.id.products_on_list);
String list = textview.getText().toString();
// Launching new Activity on selecting single List Item
Intent intent = new Intent(getActivity(), DisplayShoppingListDetailsActivity.class);
// sending data to new activity
intent.putExtra("list", list);
startActivity(intent);
}
});
//System.out.println("Test: " + Storage.getStorage().getShopingLists());
return rootView;
}
}
And this is the exception:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.widget.TextView.getText()' on a null object reference
at com.gnirt69.slidingmenuexample.fragment.Fragment1$1.onItemClick(Fragment1.java:44)
the ShoppingListAdapter:
#Override
public View getView(int position, View convertView, final ViewGroup parent){
// Get the data item for this position
//final ShoppingList list = getItem(position);
ViewHolder holder;
// Check if an existing view is being reused, otherwise inflate the view
if (convertView == null) {
convertView = View.inflate(getContext(), R.layout.items_lists_row, null);
//set up the viewHolder
holder = new ViewHolder();
holder.shoppingListTextView = (TextView) convertView.findViewById(R.id.textView1);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
// get the reference to the specific item
final ShoppingList list = getItem(position);
//TextView tv = (TextView) convertView.findViewById(R.id.textView1);
//manipulate the view
holder.shoppingListTextView.setText(list.getName());
return convertView;
}
public static class ViewHolder {
private TextView shoppingListTextView;
}
=======EDIT after solving the null pointer=======
Now it opens the new activity but it is empty, it doesn't populate the listview. I am trying yo figure out where exactly I am doing something wrong.
This is my fragment:
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.fragment1, container, false);
final ListView listView = (ListView) rootView.findViewById(R.id.listView_shopping_lists);
// get data from the table by the ListAdapter
final ShoppingListAdapter listAdapter = new ShoppingListAdapter(getActivity(), -1, Service.getService().getShoppingLists());
listView.setAdapter(listAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
ShoppingList shoppingList = listAdapter.getItem(position);
// selected item
TextView textview = (TextView) rootView.findViewById(R.id.products_on_list);
String list = textview.getText().toString();
// Launching new Activity on selecting single List Item
Intent intent = new Intent(getActivity(), DisplayShoppingListDetailsActivity.class);
// sending data to new activity
intent.putExtra("list", list);
//System.out.println(shoppingList.getProductsOnList());
startActivity(intent);
}
});
//System.out.println("Test: " + Storage.getStorage().getShopingLists());
return rootView;
}
The new activity that should display the products on the clicked list but it doesn't:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//defines the activity layout
setContentView(R.layout.shopping_list_details);
ListView listView = (ListView) findViewById(R.id.shopping_list_details);
Intent intent = getIntent();
String name = intent.getStringExtra("list");
ProductsOnListAdapter ad = new ProductsOnListAdapter(this, -1, Service.getService().getProductsOnList(name));
listView.setAdapter(ad);
}
And the adapter:
#Override
public View getView(int position, View convertView, final ViewGroup parent){
// Get the data item for this position
//final ShoppingList list = getItem(position);
ViewHolder holder;
// Check if an existing view is being reused, otherwise inflate the view
if (convertView == null) {
convertView = View.inflate(getContext(), R.layout.shopping_list_details, null);
//set up the viewHolder
holder = new ViewHolder();
holder.productsTextView = (TextView) convertView.findViewById(R.id.products_on_list);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
// get the reference to the specific item
final ProductOnList product = getItem(position);
//TextView tv = (TextView) convertView.findViewById(R.id.textView1);
//manipulate the view
holder.productsTextView.setText(product.toString());
return convertView;
}
public static class ViewHolder {
private TextView productsTextView;
}

I think the Problem is that you want to call a Textview from layout
setContentView(R.layout.shopping_list_details);
But your fragment uses the layout
final View rootView = inflater.inflate(R.layout.fragment1, container, false);
You can work around this issue by passing the TextView to your Fragment from the Main or change your xml Layout
You can test if this is true by adding a textview with the same id to the fragment1 layout.

You are referring to the same ListView R.id.listView_shopping_lists in your new Activity and your Fragment, you never target shopping_list_details in your Activity layout file which will contain each item, therefore the TextView is null.

Related

android Spinner requires 2 clicks to work

am trying to use a spinner within a fragment to categorize the output of my recycler view
when I call the recycler view function from the onCreateView it works perfectly. however, when I call it from the spinner function, it requires 2 clicks to display.
here is the spinner XML code:
<Spinner
android:id="#+id/med_spinner"
android:layout_width="150dp"
android:layout_height="30dp"
android:layout_below="#+id/tv_med2"
android:layout_marginLeft="15dp"
android:layout_marginTop="20dp"
android:layout_toRightOf="#id/tv_spinner"
android:dropDownWidth="match_parent"
android:focusable="true"
android:gravity="center"
android:entries="#array/medicine"
/>
and here is the fragment:
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.frag_medicine, container, false);
RecyclerView rv_med = view.findViewById(R.id.rv_medicine);
db = new UserDB(getActivity());
med_name = new ArrayList<>();
med_type = new ArrayList<>();
med_type2 = new ArrayList<>();
//spinner declartion
spinner = view.findViewById(R.id.med_spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getActivity(), R.array.medicine, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
//recycler view adapter and layout manger
recyclerViewAdapter = new RecyclerViewAdapterMedicine(getContext(), med_name, med_type, med_type2);
rv_med.setAdapter(recyclerViewAdapter);
rv_med.setLayoutManager(new LinearLayoutManager(getContext()));
return view;
}
and here is the spinner functions
#Override
public void onItemSelected(AdapterView<?> parent, View view, int i, long l) {
med_name.clear();
med_type.clear();
med_type2.clear();
cata = spinner.getSelectedItem().toString();
display(cata);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
cata = "All";
display(cata);
}
here's the display function:
void display(String type) {
db.open();
Cursor cursor = db.listMedicine();
if (cursor.getCount() == 0) {
Toast.makeText(getActivity(), "an error occurred", Toast.LENGTH_LONG).show();
} else {
if (type.equals("All")){
while (cursor.moveToNext()) {
med_name.add(cursor.getString(1));
med_type.add(cursor.getString(2));
med_type2.add(cursor.getString(3));
}
}else{
while (cursor.moveToNext()) {
if(cursor.getString(2).equals(type) || cursor.getString(3).equals(type)) {
med_name.add(cursor.getString(1));
med_type.add(cursor.getString(2));
med_type2.add(cursor.getString(3));
}
}
}
db.close();
}
}
I've tried to put the spinner functions within a spinner.onItemSelectedListener inside and outside the fragment, I tried to enable and disable focus and focusableTochMode, I also tried to call the recycler view before the spinner in the fragment.
You need to notify your RecyclerViewAdapter that data has changed. Add
recyclerViewAdapter.notifyDataSetChanged()
at the end of your display.

ListView inside a ListItem displays only one entry

Inside my original Activity, I initialize an Adapter to populate a ListView and that goes smoothly. ArrayList populated with all the data gets passed as an argument to the Adapter and everything goes well.
Now inside that Adapter, or that ListView that gets populated, there's another ListView and another Adapter for it.
Again, I follow the same procedure and populate the Adapter with an ArrayList, but it seems as though only the first entry gets displayed in the nested ListView. I assume this is is because the parent ListView gets populated and the data for the child ListView only populates for one parents entry.
Anyway, here's the adapter initialization and the Adapter class:
PlayerSeasonsStatsAdapter pssAdapter = new PlayerSeasonsStatsAdapter(getContext(), alPlayerSeasonsStats);
vh.lvPlayerSeasonsStats.setAdapter(pssAdapter);
alPlayerSeasonsStats is an ArrayList containing data to populate the child ListView.
Here's the child Adapter:
public class PlayerSeasonsStatsAdapter extends ArrayAdapter{
private ArrayList<PlayerStatsTeamModelSeasons> playerSeasons = new ArrayList<PlayerStatsTeamModelSeasons>();
private LayoutInflater mInflater;
public PlayerSeasonsStatsAdapter(Context context, ArrayList<PlayerStatsTeamModelSeasons> playerSeasons) {
super(context, 0, playerSeasons);
this.playerSeasons = playerSeasons;
mInflater = LayoutInflater.from(context);
}
#Override
public PlayerStatsTeamModelSeasons getItem(int position) {
return playerSeasons.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder vh;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.player_seasons_stats_row, parent, false);
vh = new ViewHolder();
vh.tvPSSRCompetition = (TextView) convertView.findViewById(R.id.tvPSSRCompetition);
vh.tvPSSRMatchesPlayed = (TextView) convertView.findViewById(R.id.tvPSSRMatchesPlayed);
vh.tvPSSRGoalsScored = (TextView) convertView.findViewById(R.id.tvPSSRGoalsScored);
vh.tvPSSRAssists = (TextView) convertView.findViewById(R.id.tvPSSRAssists);
vh.tvPSSRYellowCards = (TextView) convertView.findViewById(R.id.tvPSSRYellowCards);
vh.tvPSSRRedCards = (TextView) convertView.findViewById(R.id.tvPSSRRedCards);
vh.ivPSSRCompetitionLogo = (ImageView) convertView.findViewById(R.id.ivPSSRCompetitionLogo);
convertView.setTag(vh);
} else {
vh = (ViewHolder) convertView.getTag();
}
PlayerStatsTeamModelSeasons pstmsModel = getItem(position);
vh.tvPSSRCompetition.setText(pstmsModel.pstmSeasonModel.name);
vh.tvPSSRMatchesPlayed.setText(pstmsModel.pstmsModel.matchesPlayed);
vh.tvPSSRGoalsScored.setText(pstmsModel.pstmsModel.goalsScored);
vh.tvPSSRAssists.setText(pstmsModel.pstmsModel.assists);
vh.tvPSSRYellowCards.setText(pstmsModel.pstmsModel.yellowCards);
int totalRedCards = Integer.parseInt(pstmsModel.pstmsModel.yellowRedCards) + Integer.parseInt(pstmsModel.pstmsModel.redCards);
vh.tvPSSRRedCards.setText(totalRedCards + "");
//loadLogoToView(vh.ivPSSRCompetitionLogo, pstmsModel.pstmSeasonModel.id, true);
return convertView;
}
public static void loadLogoToView(ImageView iv, String teamId, boolean transform) {
String image = Constant.IMAGES_ROOT +
Constant.LOGO_PATH +
teamId +
Constant.LOGO_EXTENSION;
RequestCreator img = Picasso.with(iv.getContext())
.load(image);
if (transform) img.transform(new RoundedCornersTransform(2));
img.into(iv);
}
static class ViewHolder {
ImageView ivPSSRCompetitionLogo;
TextView tvPSSRCompetition;
TextView tvPSSRMatchesPlayed;
TextView tvPSSRGoalsScored;
TextView tvPSSRAssists;
TextView tvPSSRYellowCards;
TextView tvPSSRRedCards;
}
What are my options here?
Your Adapter should be look like
public class PlayerSeasonsStatsAdapter extends ArrayAdapter<PlayerStatsTeamModelSeasons> {
private class ViewHolder {
TextView tvPSSRCompetition;
}
public PlayerSeasonsStatsAdapter(Context context, List<PlayerStatsTeamModelSeasons> balanceModels) {
super(context, R.layout.row_account_balance, balanceModels);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
PlayerStatsTeamModelSeasons model = getItem(position);
PlayerSeasonsStatsAdapter.ViewHolder viewHolder;
if (convertView == null) {
viewHolder = new PlayerSeasonsStatsAdapter.ViewHolder();
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.row_account_balance, parent, false);
viewHolder.tvPSSRCompetition = (TextView) convertView.findViewById(R.id.tvPSSRCompetition);
convertView.setTag(viewHolder);
} else {
viewHolder = (PlayerSeasonsStatsAdapter.ViewHolder) convertView.getTag();
}
viewHolder.tvPSSRCompetition.setText(model.getPSSRCompetition());
if (position%2== 0) {
convertView.setBackgroundColor(Color.parseColor("#F5EEE5"));
}else{
convertView.setBackgroundColor(Color.parseColor("#FFFFFF"));
}
return convertView;
}
}
Just Call below like
PlayerSeasonsStatsAdapter adapter = new PlayerSeasonsStatsAdapter(MainActivity.this, balanceList);
listView.setAdapter(adapter);
Listview Look like bellow
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
here is row_account_balance layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<TextView
android:id="#+id/tvPSSRCompetition"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center|center_vertical|center_horizontal"
android:text="#string/agent_statement_sl"
android:textStyle="bold"
android:paddingLeft="2dp"
android:textSize="16sp"
android:paddingBottom="5dp"
android:paddingTop="5dp"/>
</LinearLayout>

Getting the correct context in an adapter and fragment

I am getting an error in my adaptor
Error:(26, 20) error: incompatible types: MainFragment cannot be converted to Activity
and I suspect that its because the type of context I am trying to use is for activities as opposed to fragments
the adaptor
public class CustomListAdapter extends ArrayAdapter<String> {
private final Activity context;
private final String[] itemname;
private final Integer[] imgid;
public CustomListAdapter(MainFragment context, String[] itemname, Integer[] imgid) {
super(context, R.layout.mylist, itemname);
// TODO Auto-generated constructor stub
this.context=context;
this.itemname=itemname;
this.imgid=imgid;
}
public View getView(int position,View view,ViewGroup parent) {
LayoutInflater inflater=context.getLayoutInflater();
View rowView=inflater.inflate(R.layout.mylist, null,true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.item);
ImageView imageView = (ImageView) rowView.findViewById(R.id.icons);
TextView extratxt = (TextView) rowView.findViewById(R.id.textView1);
txtTitle.setText(itemname[position]);
imageView.setImageResource(imgid[position]);
extratxt.setText("Description "+itemname[position]);
return rowView;
};
}
The Fragment
public class MainFragment extends Fragment {
ListView list;
String[] itemname ={
"Safari",
"Camera",
"Global"
/*"FireFox",
"UC Browser",
"Android Folder",
"VLC Player",
"Cold War"*/
};
Integer[] imgid={
R.drawable.watersensoricon,
R.drawable.ic_shutoff,
R.drawable.ic_camera,
};
public MainFragment()
{
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
// Bundle bundle = this.getArguments();
//Integer data = EventBus.getDefault().removeStickyEvent(Integer.class);
//if (data != null)
//{
// classificationGroupFilter = data.intValue();
//}
// DashboardActivity activity = (DashboardActivity) getActivity();
// int call = activity.openCallLogs();
View view = inflater.inflate(R.layout.icons_main, container, false);
//load(view);
setupList(view);
return view;
}
// #Override
private void setupList(View view){
//super.onCreate(savedInstanceState);
//setContentView(R.layout.icons_main);
CustomListAdapter adapter=new CustomListAdapter(this, itemname, imgid);
list=(ListView)view.findViewById(R.id.list);
//(ListView)view.findViewById(R.id.lv_listview);
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
String Slecteditem= itemname[+position];
//Toast.makeText(getApplicationContext(), Slecteditem, Toast.LENGTH_SHORT).show();
}
});
}
}
Layout For 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"
tools:context ="com.xera.deviceinsight.home.MainFragment">
<!-- tools:context="{relativePackage}.${activityClass}" >-->
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" >
</ListView>
</RelativeLayout>
Change
CustomListAdapter adapter=new CustomListAdapter(this, itemname, imgid);
To
CustomListAdapter adapter=new CustomListAdapter(getActivity(), itemname, imgid);
Because in your case this is link to MainFragment, not to Activity.
Adapter require context of an Activity. You can use getActivity() method of the fragment for accessing the Activity context. Mind you, you need to make sure that the fragment is attached to an Activity.
So to fix this replace following
CustomListAdapter adapter=new CustomListAdapter(this, itemname, imgid);
with
CustomListAdapter adapter=new CustomListAdapter(getActivity(), itemname, imgid);
you can use
viewGroup.getContext()
in onCreateViewHolder, or
viewHolder.getView().getContext()
in onBindViewHolder

How to make phonecall from one of the arraylist's element onclick?

I have an ArrayList with tree elements in it (icon, text(name), text(phonenumber)).
I want to do two things,
1) make whole one element of list clickable
2) make phone call to that number onclick
Now I know I need to use onclicklistener but how do implement it to my code? My main and adapter
public class MainActivity extends ListActivity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.target_item);
// if extending Activity
//setContentView(R.layout.activity_main);
// 1. pass context and data to the custom adapter
MyAdapter adapter = new MyAdapter(this, generateData());
// if extending Activity 2. Get ListView from activity_main.xml
//ListView listView = (ListView) findViewById(R.id.listview);
// 3. setListAdapter
//listView.setAdapter(adapter); if extending Activity
setListAdapter(adapter);
}
private ArrayList<Model> generateData() {
ArrayList<Model> models = new ArrayList<Model>();
// here are elements of the arraylist header & next are list's elements
models.add(new Model("[text]"));
models.add(new Model(R.drawable.[icon], "[text]", "**[text(number)]**"));
models.add(new Model(R.drawable.[icon2], "[text2]", "**[text(number2)]**"));
return models;
}
}
public class MyAdapter extends ArrayAdapter<Model> {
private final Context context;
private final ArrayList<Model> modelsArrayList;
public MyAdapter(Context context, ArrayList<Model> modelsArrayList) {
super(context, R.layout.target_item, modelsArrayList);
this.context = context;
this.modelsArrayList = modelsArrayList;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// 1. Create inflater
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// 2. Get rowView from inflater
View rowView = null;
if(!modelsArrayList.get(position).isGroupHeader()){
rowView = inflater.inflate(R.layout.target_item, parent, false);
// 3. Get icon,title & counter views from the rowView
ImageView imgView = (ImageView) rowView.findViewById(R.id.item_icon);
TextView titleView = (TextView) rowView.findViewById(R.id.item_title);
TextView counterView = (TextView) rowView.findViewById(R.id.item_counter);
// 4. Set the text for textView
imgView.setImageResource(modelsArrayList.get(position).getIcon());
titleView.setText(modelsArrayList.get(position).getTitle());
counterView.setText(modelsArrayList.get(position).getCounter());
}
else{
rowView = inflater.inflate(R.layout.group_header_item, parent, false);
TextView titleView = (TextView) rowView.findViewById(R.id.header);
titleView.setText(modelsArrayList.get(position).getTitle());
}
// 5. retrn rowView
return rowView;
}
}
Try this-
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
makeCall("Phone Number goes here..");
}
});
public void makeCall(String callTo) {
Intent callIntent = new Intent(Intent.ACTION_DIAL);
callIntent.setData(Uri.parse("tel:" + callTo));
startActivity(callIntent);
}
In you MyAdapter.class to make change like
rowview.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:0377778888"));
// hear set your array position vise set mobile nmber
startActivity(callIntent);
}
});

onclicklistener for button in a list

I have a project in android studio with a custom listview. my custom listview contains 2textbox and a switch and imagebutton but i cant find out how to set onclicklistener or another listeners for them in listadapter class
here is my listadapter:
public class listadapter extends ArrayAdapter {
Context context_;
int resource_;
ArrayList<reminders> objects_;
boolean bool;
DBAdapter db;
public listadapter(Context context, int resource, ArrayList<reminders> objects) {
super(context, resource, objects);
context_ = context;
resource_ = resource;
objects_ = objects;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context_.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View ViewRow = inflater.inflate(R.layout.reminders_list_layout, parent, false);
TextView nametxt, addresstxt;
Switch sw;
ImageView imgview;
nametxt = (TextView) ViewRow.findViewById(R.id.remindername);
addresstxt = (TextView) ViewRow.findViewById(R.id.reminderaddress);
sw = (Switch) ViewRow.findViewById(R.id.remindersw);
imgview = (ImageView) ViewRow.findViewById(R.id.imageView4);
nametxt.setText(objects_.get(position).name);
addresstxt.setText(objects_.get(position).address);
bool = (objects_.get(position).swbool != 0);
sw.setChecked(bool);
imgview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View parentRow = (View) v.getParent();
ListView listView = (ListView) parentRow.getParent();
final int position = listView.getPositionForView(parentRow);
Toast.makeText(context_,position+"",Toast.LENGTH_LONG).show();
}
});
return ViewRow;
}
but when I'm testing my project and clicking on imageview it gives me forceclose and this error in logcat
12-27 20:58:50.343 5658-5658/com.amir_p.yadambendaz E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.amir_p.yadambendaz, PID: 5658
java.lang.ClassCastException: android.widget.LinearLayout cannot be cast to android.widget.ListView at com.amir_p.yadambendaz.listadapter$1.onClick(listadapter.java:49)
what can I do?
Try changing
public View getView(int position, View convertView, ViewGroup parent) {
...
#Override
public void onClick(View v) {
View parentRow = (View) v.getParent();
ListView listView = (ListView) parentRow.getParent();
...
}
to
public View getView(int position, View convertView, final ViewGroup parent) {
...
#Override
public void onClick(View v) {
ListView listView = (ListView) parent;
...
}
Simplest way is using tag.
You can use following code.
imgview.setTag(new Integer(position);
imgview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final int position = (Integer)v.getTag();
Toast.makeText(context_,position+"",Toast.LENGTH_LONG).show();
}
});
If you want to save other object in tag, you can use setTag(int key, Object object) for saving postion.
For getting Listview, you can use following code.
ListView listview = (ListView) v.getParent() //item view
.getParent() //Linear Layout in listview
.getParent();//ListView
View parentRow = (View) v.getParent();
ListView listView = (ListView) parentRow.getParent();
You are writing a listener for imageview and getting an parent from an image will return a row of listview. Here parentRow.getParent() is an row in listView which is a layout and you are casting it to listview.

Categories