buttons doesn't work inside a ListView - java

I have a Button inside a ListView.
I want to go to another Activity when it is clicked.
But I get this error:
No enclosing instance of the type Appointment is accessible in scope
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.item_row, null);
TextView txtsection = (TextView)vi.findViewById(R.id.section);
TextView txtdoctor = (TextView)vi.findViewById(R.id.doctor);
TextView txtdate = (TextView)vi.findViewById(R.id.date);
TextView txttime = (TextView)vi.findViewById(R.id.time);
btchange = (Button)vi.findViewById(R.id.change);
btchange.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(context, Available.class);
startActivity(i);
}
});
btdelete = (Button)vi.findViewById(R.id.delete);
txtsection.setText(item.section);
txtdoctor.setText(item.doctor);
txtdate.setText(item.date);
txttime.setText(item.time);
return vi; }}

At line
Intent i = new Intent(Appointment.this,Available.class);
Appointment.this is valid only if the adaptar is an inner class of Appointment.
If is not the case, use the Context passed to the adapter.
Intent i = new Intent(context, Available.class);
Declare a private field, named context, in your adapter:
private Context context;
In the adapter constructor, assign the context passed to it:
this.context = context;
Change the getView method to this:
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
if( convertView == null ){
convertView = inflater.inflate(R.layout.yourListLayout, parent, false);
}
Button btchange = (Button)convertView.findViewById(R.id.yourbuttonid);
btchange.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(context, Available.class);
startActivity(i);
}
});
return convertView;
}
EDIT
btChange also need to point to the button that has clicked as playmaker420 said.
I edited the code to accomplish that.
EDIT 2
Change your code adapter to this:
package com.example.clinic;
public class CustomListViewAdapter extends BaseAdapter
{
private Context context;
Button btchange,btdelete;
LayoutInflater inflater;
List<ListViewItem> items;
public CustomListViewAdapter(Activity context, List<ListViewItem> items) {
super();
this.context = context;
this.items = items;
this.inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return items.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.item_row, null);
//add
ListViewItem item = items.get(position);
TextView txtsection = (TextView)vi.findViewById(R.id.section);
TextView txtdoctor = (TextView)vi.findViewById(R.id.doctor);
TextView txtdate = (TextView)vi.findViewById(R.id.date);
TextView txttime = (TextView)vi.findViewById(R.id.time);
btchange = (Button)vi.findViewById(R.id.change);
btchange.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(context, Available.class);
//updated
context.startActivity(i);
}
});
btdelete = (Button)vi.findViewById(R.id.delete);
txtsection.setText(item.section);
txtdoctor.setText(item.doctor);
txtdate.setText(item.date);
txttime.setText(item.time);
return vi;
}

Intent i = new Intent(Appointment.this,Available.class);
startActivity(i);

Related

getView not called on baseAdapter class using Android Studio

I have use this class extends base adapter display values. Below code working eclipse correctly. but me newly created project using Androi Studio there this code getview function not call or working.
i also check getcount . getcount values available.
public class CustomAdapterChatActivity extends BaseAdapter {
ArrayList<ChatUsersDetailsBean> mBeans = new ArrayList<ChatUsersDetailsBean>();
Context mcontext;
LayoutInflater inflater;
CommonUtil commonUtil;
public CustomAdapterChatActivity(Context context,
ArrayList<ChatUsersDetailsBean> mBeans) {
// TODO Auto-generated constructor stub
mcontext = context;
this.mBeans = mBeans;
commonUtil = new CommonUtil(context);
inflater = (LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return mBeans.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public class Holder {
TextView name;
TextView content;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Log.e("getView",""+"getView");
if (convertView == null) {
convertView = inflater.inflate(
R.layout.chat_listview_layout_screen, null);
}
setAttributes(position, convertView);
convertView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
click(position);
}
});
return convertView;
}
public void click(int position) {
Intent mintent = new Intent(mcontext, ChatViewBackgroundActivity.class);
mintent.putExtra("name", mBeans.get(position).getOpponent_name());
((ChatActivity) mcontext).startActivityForResult(mintent, 1);
}
public void setAttributes(final int position, View convertView) {
Holder holder = new Holder();
holder.imgdispatcher = (ImageView) convertView
.findViewById(R.id.chat_list_iv_profilepic);
}
Please help me. i struggle this part.
No error will be displayed.
i check getview run or not that time getview not working anytime.
this code any changes needed
Change your getView() method in your adapter class like below code:
public View getView (final int position, View convertView, ViewGroup parent){
if( convertView == null ){
//We must create a View:
convertView = inflater.inflate(R.layout.my_list_item, parent, false);
}
//Here we can do changes to the convertView
return convertView;
}
While adding newly inflated view, try to avoid passing null as view root. Lint will now warn you not to pass in null for root. Your app won’t crash in this scenario, but it can misbehave. When your child View doesn’t know the correct LayoutParams for its root ViewGroup, it will try to determine them on its own using generateDefaultLayoutParams.
#AbiK If you already done like I mentioned on above comment means, use below code of modified getView() method and setAttributes() method. I hope It works for you.
public class CustomAdapterChatActivity extends BaseAdapter {
ArrayList<ChatUsersDetailsBean> mBeans;
Context mcontext;
LayoutInflater inflater;
CommonUtil commonUtil;
public CustomAdapterChatActivity(Context context,
ArrayList<ChatUsersDetailsBean> mBeans) {
mcontext = context;
this.mBeans = mBeans;
commonUtil = new CommonUtil(context);
}
#Override
public int getCount() {
return mBeans.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public class Holder {
TextView name;
TextView content;
ImageView imgdispatcher;
}
public Holder setAttributes(final int position, View convertView) {
Holder holder = new Holder();
holder.imgdispatcher = (ImageView) convertView.findViewById(R.id.chat_list_iv_profilepic);
// holder.name=(TextView)convertView.findViewById(R.id.); // declare Id
// holder.content=(TextView)convertView.findViewById(R.id.); // declare Id
return holder;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
Holder holder = null;
LayoutInflater inflater = (LayoutInflater)
mcontext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.chat_listview_layout_screen, parent, false);
holder = setAttributes(position, convertView);
convertView.setTag(holder);
} else {
holder = (Holder) convertView.getTag();
}
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
click(position);
}
});
return convertView;
}
public void click(int position) {
Intent mintent = new Intent(mcontext, ChatViewBackgroundActivity.class);
mintent.putExtra("name", mBeans.get(position).getOpponent_name());
((ChatActivity) mcontext).startActivityForResult(mintent, 1);
}
}

Fix Number Of Column And Row in Grid View

I am Listing all the Apps installed on device in Fragment which having gridview inside. what i want to do is, i want 4 col * 5 rows(20 App in one fragment only) , if i install new app (app count 21) it must set on the next fragment and set at the top left of new fragment , fragment should generate dynamically , and add to viewpager.
here is my code. MainActivity :
public class MainActivity extends FragmentActivity {
ViewPager pager;
AppViewAdapter adapter;
GridFrag gridFrag;
FragmentManager fragmentManager;
FragmentTransaction transaction;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bindView();
init();
addListener();
}
private void bindView() {
pager = (ViewPager) findViewById(R.id.slideingpager);
}
private void init() {
adapter = new AppViewAdapter(getSupportFragmentManager());
pager.setAdapter(adapter);
}
}
GridFragment.java :
public class GridFrag extends android.support.v4.app.Fragment implements
OnItemClickListener {
GridView gridView;
ViewAdapter viewAdapter;
PackageManager packageManager;
int columnsOfGridView;
public class AppDetails {
Drawable icon;
String label;
}
AppDetails packages[];
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.gridfrag, container, false);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
packageManager = getActivity().getPackageManager();
gridView = (GridView) getActivity().findViewById(R.id.grid);
final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
List<ResolveInfo> packList = packageManager.queryIntentActivities(
mainIntent, 0);
packages = new AppDetails[packList.size()];
for (int i = 0; i < packList.size(); i++) {
packages[i] = new AppDetails();
packages[i].icon = packList.get(i).loadIcon(packageManager);
packages[i].label = packList.get(i).loadLabel(packageManager)
.toString();
}
viewAdapter = new ViewAdapter(getActivity(), packages);
gridView.setAdapter(viewAdapter);
int totalApps = gridView.getCount();
Toast.makeText(getActivity(), "Total "+ totalApps + " App(s)Found",Toast.LENGTH_SHORT).show();
gridView.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
Toast.makeText(getActivity(),
"You Clicked on : " + packages[position].label,
Toast.LENGTH_SHORT).show();
}
}
ViewAdapter.java (GridAdapter)
public class ViewAdapter extends BaseAdapter {
private Context context;
AppDetails setPacksForAdapter[];
public ViewAdapter(Context c, AppDetails apps[]) {
context = c;
setPacksForAdapter = apps;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return setPacksForAdapter.length;
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
public static class ViewHolder {
ImageView imgDefaultAppIcon;
TextView tvDefaultAppLabel;
}
#Override
public View getView(int pos, View v, ViewGroup parent) {
// TODO Auto-generated method stub
ViewHolder holder = new ViewHolder();
if (v == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = inflater.inflate(R.layout.grid_view, null);
holder.imgDefaultAppIcon = (ImageView) v
.findViewById(R.id.ivAppIcon);
holder.tvDefaultAppLabel = (TextView) v
.findViewById(R.id.tvAppLabel);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
holder.imgDefaultAppIcon.setImageDrawable(setPacksForAdapter[pos].icon);
holder.tvDefaultAppLabel.setText(setPacksForAdapter[pos].label);
return v;
}
}
AppViewAdepter.java (For ViewPager)
public class AppViewAdapter extends FragmentPagerAdapter {
List<Fragment> fragmentsList;
public AppViewAdapter(FragmentManager fm) {
super(fm);
this.fragmentsList = new ArrayList<Fragment>();
for (int i = 0; i <= 2; i++) {
if (i % 2 == 0)
fragmentsList.add(new GridFrag());
else
fragmentsList.add(new FragTwo());
}
}
#Override
public Fragment getItem(int arg0) {
return fragmentsList.get(arg0);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return fragmentsList.size();
}
}
Set Layoutparams dynamically height of rootview of single grid in Adapter in getView() Method
(Device height / 5) - statusBarHieght
Some code : in getView() of Adapter
int grid_height = ((Helper.get_device_height(context)) / 5) - statusBarHeight;
GridView.LayoutParams layoutParams = (android.widget.AbsListView.LayoutParams) view.getLayoutParams();
layoutParams.height = grid_height;
view.setLayoutParams(layoutParams);
and,
gridview XML set columns=4
It will solve your problem.
Hope it will help you !
in your layout.xml by default <android:columnCount="auto_fit"> is set, you have to change it to as 4 by dong this <android:columnCount="4"> and to set rows similarly also in java you can do this like following setColumnCount(4) and setRowCount(5)

click to start new activity in grid view

I have grid view in my application. on click of each image in gridview new activity should start.
now when I click on them, a toast appears.
how I manage setOnClicklistener in my adaptor I can't have startactivity.
enter code here:
public class CustomAdapter extends BaseAdapter {
String [] result;
Context context;
int [] imageId;
private static LayoutInflater inflater=null;
public CustomAdapter(MyActivity mainActivity, String[] prgmNameList, int[] prgmImages) {
// TODO Auto-generated constructor stub
result=prgmNameList;
context=mainActivity;
imageId=prgmImages;
inflater = (LayoutInflater)context.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return result.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public class Holder
{
TextView tv;
ImageView img;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final Holder holder=new Holder();
View rowView;
rowView = inflater.inflate(R.layout.program_list, null);
holder.tv=(TextView) rowView.findViewById(R.id.textView1);
holder.img=(ImageView) rowView.findViewById(R.id.imageView1);
holder.tv.setText(result[position]);
holder.img.setImageResource(imageId[position]);
rowView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(context, "You Clicked "+result[position], Toast.LENGTH_LONG).show();
}
});
return rowView;
}
and here is myactivity:
public class MyActivity extends Activity {
GridView gv;
Context context;
ArrayList prgmName;
public static String [] prgmNameList={"Let Us C","c++","JAVA","Jsp","Microsoft .Net","Android","PHP","Jquery","JavaScript"};
public static int [] prgmImages={R.drawable.images,R.drawable.images1,R.drawable.images2,R.drawable.images3,R.drawable.images4,R.drawable.images5,R.drawable.images6,R.drawable.images7,R.drawable.images8};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
gv=(GridView) findViewById(R.id.gridView1);
gv.setAdapter(new CustomAdapter(this, prgmNameList,prgmImages));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Add onItemClickListener on GridView
gv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
if(position==0){
Intent iinent= new Intent(MyActivity.this,secondactivity.class);
startActivity(iinent);
}
}
});

Can not identify the cause of Application crash

I have this following class which when runs and comes to a certain line in the class the application crashes. If i comment out that line the application runs well. When i look at the logcat i don't find any CausedBy Text. So can not figure out the cause of this crash. Someone please help me out to solve this.
public class Secondscreen extends Activity {
int total=0;
final ArrayList<Listitem> arrayList=new ArrayList<Listitem>();
BaseAdapter adapter =null;
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.secondscreen);
ListView lv= (ListView) findViewById(R.id.listView1);
final TextView showtotal = (TextView) findViewById(R.id.totalprice);
final Button thirdBtn = (Button) findViewById(R.id.third);
final Controller aController = (Controller) getApplicationContext();
final int cartSize = aController.getCart().getCartSize();
//Addition of item to arraylist
if(cartSize >0)
{
for(int i=0;i<cartSize;i++)
{
String pName = aController.getCart().getProducts(i).getProductName();
int pPrice = aController.getCart().getProducts(i).getProductPrice();
int pQuantity = aController.getCart().getProducts(i).getProductQuantity();
String pDisc = aController.getCart().getProducts(i).getProductDesc();
total = total + pPrice;
Listitem item=new Listitem(pName, pPrice, pDisc, pQuantity);
Log.e("quantity", ""+pQuantity);
Log.e("Intem's quantity", ""+item.getQuantity());
arrayList.add(item);
Log.e("Arraylist item quantity", ""+arrayList.get(i).getQuantity());
}
showtotal.setText(""+total);
}
adapter= new BaseAdapter(){
#Override
public int getCount() {
// TODO Auto-generated method stub
return arrayList.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return arrayList.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
LayoutInflater inflater=(LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
#Override
public View getView(final int position, View view, ViewGroup viewgroup) {
if (view == null) {
view=inflater.inflate(R.layout.pattern, null);
}
TextView tv=(TextView) view.findViewById(R.id.nameview);
TextView tv2=(TextView) view.findViewById(R.id.pdesc);
TextView tv3=(TextView) view.findViewById(R.id.priceView);
TextView tv4=(TextView) view.findViewById(R.id.quantityView);
Button btn=(Button) view.findViewById(R.id.patternButton);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
int tempstore=arrayList.get(position).getPrice();
total=total-tempstore;
arrayList.remove(position);
showtotal.setText(""+total);
ModelProducts tempProductObject = aController.getProducts(position);
aController.getCart().removeProducts(tempProductObject);
adapter.notifyDataSetChanged();
int cartSize2 = aController.getCart().getCartSize();
}
});
tv.setText(arrayList.get(position).getName());
tv2.setText(""+arrayList.get(position).getPrice());
tv3.setText(arrayList.get(position).getDesc());
tv4.setText(arrayList.get(position).getQuantity()); //<-this is the line which when gets executed causes the application to crash.
return view;
}
};
lv.setAdapter(adapter);
}
}
yes getQuantity() returns an int value
So change this
tv4.setText(arrayList.get(position).getQuantity());
to
tv4.setText(String.valueOf(arrayList.get(position).getQuantity()));
What happens is setText(int) looks for a Resource with the int value if not found you end up getting ResourceNotFoundException
What you want is setText(CharacterSequence) so you need use String.valueof(intvalue)

Listview click is not fire.

I created custom adapter for listview which contain text and images, on click of particular list item I have to open another activity, but I am not able to fire listview click event, below is my code.
Thanks.
Adapter
public class ImageAndTextAdapter extends ArrayAdapter<String> {
private LayoutInflater mInflater;
private Context myCtx;
private String[] mStrings;
private TypedArray mIcons;
private int mViewResourceId;
public ImageAndTextAdapter(Context ctx, int viewResourceId,
String[] strings, TypedArray icons) {
super(ctx, viewResourceId, strings);
myCtx = ctx;
mInflater = (LayoutInflater)ctx.getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
mStrings = strings;
mIcons = icons;
mViewResourceId = viewResourceId;
}
#Override
public int getCount() {
return mStrings.length;
}
#Override
public String getItem(int position) {
return mStrings[position];
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = mInflater.inflate(mViewResourceId, null);
ImageView iv = (ImageView)convertView.findViewById(R.id.option_icon);
iv.setImageDrawable(mIcons.getDrawable(position));
TextView tv = (TextView)convertView.findViewById(R.id.option_text);
tv.setText(mStrings[position]);
return convertView;
}
}
Main acitivity
public class OurWishingWellActivity extends ListActivity implements OnClickListener{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// setContentView(R.layout.list_view_image);
Context ctx = getApplicationContext();
Resources res = ctx.getResources();
String[] options = res.getStringArray(R.array.reg_item_names);
TypedArray icons = res.obtainTypedArray(R.array.reg_icons);
setListAdapter(new ImageAndTextAdapter(ctx, R.layout.list_item,
options, icons));
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
}
Respected Aafag#
You have write onclick of listview like below.
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
Toast.makeText(AdvancedListViewActivity.this, "working", Toast.LENGTH_SHORT).show();
System.out.println("working!!!!!!!!!");
}
Add listener
#Override
public View getView(int position, View convertView, ViewGroup parent) {
convertView = mInflater.inflate(mViewResourceId, null);
ImageView iv = (ImageView)convertView.findViewById(R.id.option_icon);
iv.setImageDrawable(mIcons.getDrawable(position));
TextView tv = (TextView)convertView.findViewById(R.id.option_text);
tv.setText(mStrings[position]);
convertView .setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity();
}
});
return convertView;
}

Categories

Resources