Pass extra values to getView onClick method - android

Sorry just a noob here, my boss handed this to me from the former developer and I don't anything about android. My question is how do I pass extra dynamic values inside getView > onClick method so that accessible to me.
categoryCursorAdaptor
class categoryCursorAdaptor extends BaseAdapter {
Context context;
String[] data;
private static LayoutInflater inflater = null;
public categoryCursorAdaptor(Context context, String[] data) {
this.context = context;
this.data = data;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return data.length;
}
#Override
public Object getItem(int position) {
return data[position];
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (vi == null) vi = inflater.inflate(R.layout.item_category, null);
TextView text = (TextView) vi.findViewById(R.id.specialCatItemName);
text.setText(data[position]);
Button Button1= (Button) vi.findViewById(R.id.btnSpecialView);
Button1.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
//Access extra values here
}
});
return vi;
}
}
CategoryActivity
String[] catValsArr = new String[arrayCatVals.size()];
catValsArr = arrayCatVals.toArray(catValsArr);
lvSpecialCatList = (ListView) findViewById(R.id.lvSpecialCatList);
lvSpecialCatList.setAdapter(new categoryCursorAdaptor(this, catValsArr));

You already have position inside getView(....) so use that to get proper data from String Array
String myData = data[position]; //Use myData
under onClick(...)

Related

Error in code for jump to other fragment when the button in the listview clicked

Hey there,
here i have created list view with image and button.I want to handle that button by jump to other fragment.For that i have used this code in onclick listner of button but it's wrong.
It shows error "can not resolve method getFragmentManager()".What and where should i do correction in onclicklistner code of button? Please help.
Here is my adapter file for list view.
Cart_ContactAdapter.java:
public class Cart_ContactAdapter extends ArrayAdapter{
List list = new ArrayList();
public Cart_ContactAdapter(#NonNull Context context, #LayoutRes int resource) {
super(context, resource);
}
public void add(Contacts object) {
super.add(object);
list.add(object);
}
#Override
public int getCount() {
return list.size();
}
#Nullable
#Override
public Object getItem(int position) {
return list.get(position);
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View row;
ContactHolder contactHolder;
row = convertView;
if(row==null){
LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.cart_list_pattern,parent,false);
contactHolder=new ContactHolder();
contactHolder.t_product_name= (TextView) row.findViewById(R.id.productname);
contactHolder.t_product_cn= (TextView) row.findViewById(R.id.productcn);
contactHolder.t_quantity= (TextView) row.findViewById(R.id.quantity);
contactHolder.t_price= (TextView) row.findViewById(R.id.price);
contactHolder.buynow= (Button) row.findViewById(R.id.buynow);
contactHolder.buynow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
TextView product_name= (TextView) view.findViewById(R.id.productname);
TextView product_cn= (TextView) view.findViewById(R.id.productcn);
PurchaseFragment p = new PurchaseFragment ();
Bundle args = new Bundle();
args.putString("product_name",product_name.getText().toString());
args.putString("product_cn", product_cn.getText().toString());
p.setArguments(args);
/*it shows error on this line*/getFragmentManager().beginTransaction().add(R.id.content_frame, p).addToBackStack("organic acid").commit();
}
});
row.setTag(contactHolder);
}
else
{
contactHolder= (ContactHolder) row.getTag();
}
Contacts contacts = (Contacts) this.getItem(position);
contactHolder.t_product_name.setText(contacts.getProduct_name());
contactHolder.t_product_cn.setText(contacts.getProduct_cn());
contactHolder.t_quantity.setText(contacts.getQuantity());
contactHolder.t_price.setText(contacts.getPrice());
return row;
}
static class ContactHolder{
TextView t_product_name,t_product_cn,t_quantity,t_price;
Button buynow;
}
You can't use getFragmentManager() unless you are inside an activity.
So if you are sure that the context you pass in the constructor is an activity you can make it global and use it to call getFragmentManager().
Like this:
public class Cart_ContactAdapter extends ArrayAdapter{
//Declare a global context
private Context context;
List list = new ArrayList();
public Cart_ContactAdapter(#NonNull Context context, #LayoutRes int resource) {
super(context, resource);
//Make context global
this.context=context;
}
public void add(Contacts object) {
super.add(object);
list.add(object);
}
#Override
public int getCount() {
return list.size();
}
#Nullable
#Override
public Object getItem(int position) {
return list.get(position);
}
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View row;
ContactHolder contactHolder;
row = convertView;
if(row==null){
LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = layoutInflater.inflate(R.layout.cart_list_pattern,parent,false);
contactHolder=new ContactHolder();
contactHolder.t_product_name= (TextView) row.findViewById(R.id.productname);
contactHolder.t_product_cn= (TextView) row.findViewById(R.id.productcn);
contactHolder.t_quantity= (TextView) row.findViewById(R.id.quantity);
contactHolder.t_price= (TextView) row.findViewById(R.id.price);
contactHolder.buynow= (Button) row.findViewById(R.id.buynow);
contactHolder.buynow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
TextView product_name= (TextView) view.findViewById(R.id.productname);
TextView product_cn= (TextView) view.findViewById(R.id.productcn);
PurchaseFragment p = new PurchaseFragment ();
Bundle args = new Bundle();
args.putString("product_name",product_name.getText().toString());
args.putString("product_cn", product_cn.getText().toString());
p.setArguments(args);
//Cast the context to an activity but be sure that it's an Activity or AppCompatActivity,Then use it to call getFragmentManager();
((Activity)context).getFragmentManager().beginTransaction().add(R.id.content_frame, p).addToBackStack("organic acid").commit();
}
});
row.setTag(contactHolder);
}
else
{
contactHolder= (ContactHolder) row.getTag();
}
Contacts contacts = (Contacts) this.getItem(position);
contactHolder.t_product_name.setText(contacts.getProduct_name());
contactHolder.t_product_cn.setText(contacts.getProduct_cn());
contactHolder.t_quantity.setText(contacts.getQuantity());
contactHolder.t_price.setText(contacts.getPrice());
return row;
}
static class ContactHolder{
TextView t_product_name,t_product_cn,t_quantity,t_price;
Button buynow;
}

Listview Scrolling changes Button Visibility?

I am having a listview in my App. Each row has an button. I'm hiding the button for some rows with setVisibility. But the buttons visibility changes after scrolling the list. How can i stop this change ?
I already saw a question with the checkbox with Listview. But i don't know how to implement it for the buttons. So please guide me!
ADAPTER
public class published_adapter extends BaseAdapter {
Context con;
ArrayList<HashMap<String, String>> class_list;
LayoutInflater inflater;
public class ViewHolder
{
TextView title,description,class_section,date;
ImageButton download;
Button viewasgn;
}
public published_adapter(Context co, ArrayList<HashMap<String, String>> list1) {
class_list = list1;
con = co;
inflater = (LayoutInflater) con.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return class_list.size();
}
#Override
public Object getItem(int arg0) {
return class_list.get(arg0).get("class_name");
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public View getView(final int arg0, View arg1, ViewGroup arg2) {
View row = arg1;
ViewHolder holder = new ViewHolder();
if(row == null)
{
row = inflater.inflate(
R.layout.assignment_adapter_layout, arg2, false);
// initialize the elements
holder.download = (ImageButton) row.findViewById(R.id.download);
holder.title = (TextView) row.findViewById(R.id.title);
holder.description = (TextView) row.findViewById(R.id.description);
holder.class_section = (TextView) row.findViewById(R.id.class_section);
holder.date = (TextView) row.findViewById(R.id.date);
holder.viewasgn = (Button) row.findViewById(R.id.attend);
row.setTag(holder);
}
else
{
holder = (ViewHolder)row.getTag();
}
String type = class_list.get(arg0).get("ASSIGNMENT_TYPE");
if (class_list.get(arg0).get("TOTAL_SUBMISSION").equals("0")) {
Log.e("TITLE", class_list.get(arg0).get("TOTAL_SUBMISSION"));
}
else{
Log.e("TITLE", class_list.get(arg0).get("TOTAL_SUBMISSION"));
holder.viewasgn.setVisibility(View.VISIBLE);
holder.viewasgn.setText("VIEW");
}
return row;
}
}
Update your code like this
if (class_list.get(arg0).get("TOTAL_SUBMISSION").equals("0")) {
Log.e("TITLE", class_list.get(arg0).get("TOTAL_SUBMISSION"));
holder.viewasgn.setVisibility(View.INVISIBLE);
holder.viewasgn.setText("");
}
else{
Log.e("TITLE", class_list.get(arg0).get("TOTAL_SUBMISSION"));
holder.viewasgn.setVisibility(View.VISIBLE);
holder.viewasgn.setText("VIEW");
}
Either add the setVisibility(View.INVISIBLE) like #Solhail suggested or hide those buttons by default in your assignment_adapter_layout.xml by adding android:visibility="invisible" in your Button's properties, and don't change a thing in your current adapter code.
In your case Views will be recreated when listView is scroll.
To prevent this, you should not use ViewHolder.
You need to user Adapter like this:
(Only if you have not a lot elements)
public class SampleAdapter extends BaseAdapter {
private ArrayList<String> arrayList;
private Activity activity;
public SampleAdapter(ArrayList<String> arrayList, Activity activity) {
this.arrayList = arrayList;
this.activity = activity;
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public Object getItem(int position) {
return arrayList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater layoutInflater = activity.getLayoutInflater();
View view = layoutInflater.inflate(R.layout.sample_element, parent, false);
TextView textViewTitle = (TextView) view.findViewById(R.id.text_view_title);
textViewTitle.setText(arrayList.get(position));
return view;
} }

Method call expected in Android BaseAdapter

I'm trying to extend a BaseAdapter to make my custom listview. But it says:
method call expected` in the getCount() method.
I know it's an Array, so how do I fetch it? I'm basically a nube in this field. Here is my code I have tried to apply:
public class customAdapter extends BaseAdapter implements View.OnClickListener {
private Context context;
private String[] restaurant;
private String[] address;
private String[] time;
private static LayoutInflater layoutInflater = null;
public Resources res;
int image[];
ListModel tempvalues = null;
int i=0;
public customAdapter(MainActivity mainActivity, String[] rest, String[] add,String[] tim,int[] img){
restaurant = rest;
context=mainActivity;
address= add;
time = tim;
image = img;
layoutInflater = (LayoutInflater)context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return restaurant.length(); // Method call expected.
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
public class Holder{
TextView resname;
TextView resadd;
TextView restim;
ImageView imageView;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Holder holder = new Holder();
View rowview;
rowview = layoutInflater.inflate(R.layout.custom_list_view_for_restaurant_names,null);
holder.resname = (TextView)rowview.findViewById(R.id.resnameTextView);
holder.resadd = (TextView)rowview.findViewById(R.id.address_textview);
holder.restim = (TextView)rowview.findViewById(R.id.time_textview);
holder.imageView = (ImageView)rowview.findViewById(R.id.imageView);
holder.resname.setText(restaurant[position]);
holder.resadd.setText(address[position]);
holder.restim.setText(time[position]);
holder.imageView.setImageResource(image[position]);
rowview.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
return rowview;
}
#Override
public void onClick(View v) {
}
}
Change
return restaurant.length();
to
return restaurant.length;
restaurant is a Array not a List
And one more thing I would like to suggest you,
Do not pass these arrays separately, because that will logically break the code, if some array size becomes less than the restaurant array.
I suggest you to use a model,
eg:
public class Event {
private String restaurant;
private String address;
private String time;
private int image;
//getters and setters
}
and pass a list of Event s
like below,
private List<Event> events;
public customAdapter(MainActivity mainActivity, List<Event> events){
this.events = events;
layoutInflater = (LayoutInflater)context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return events.size(); // Method call expected.
}
#Override
public Object getItem(int position) {
return events.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
and access that,
Event event = events.get(position);
holder.resname.setText(event.getResturant());
holder.resadd.setText(event.getAddress());
holder.restim.setText(event.getTime());
holder.imageView.setImageResource(event.getImage());
And also,
You should not inflate the ListView Elements all the time you should reuse the already inflated elements.
View view = convertView;
if (view == null) {
// if it's not recycled, initialize some attributes
LayoutInflater inflater = (LayoutInflater) this.context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.custom_list_view_for_restaurant_names,null);
}

how to get listview item on button click and save to sqlite

I've four textviews and a button in listview. when user clicks on the button i want to get the value of these four textviews and pass to the database. I'm confuse how to save the data of selected item to sqlite.
public class PlannningListViewAdapter extends BaseAdapter{
Context context;
public ArrayList<Planning> planArraylist;
private static LayoutInflater inflater = null;
public Activity planActivity;
public PlannningListViewAdapter(Context context,
ArrayList<Planning> planArraylist) {
this.context = context;
this.planArraylist = planArraylist;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return planArraylist.size();
}
#Override
public Object getItem(int arg0) {
return arg0;
}
#Override
public long getItemId(int arg0) {
return arg0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
convertView = inflater.inflate(R.layout.single_lv_item, null);
}
Planning p = planArraylist.get(position);
TextView tvDocCode = (TextView) convertView.findViewById(R.id.Plan_no);
TextView tvDocName = (TextView) convertView.findViewById(R.id.doc_name);
TextView tvmon = (TextView) convertView.findViewById(R.id.mon);
TextView tvAdr = (TextView) convertView.findViewById(R.id.adr);
Button btn_save =(Button)convertView.findViewById(R.id.button1);
btn_save.setOnClickListener(ButtonClickListener);
tvDocCode.setText(p.getDocCode());
tvDocName.setText(p.getDocName());
tvmon.setText(p.getTerrCode());
tvAdr.setText(p.getAdr());
return convertView;
}
private OnClickListener ButtonClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
final int position = mListView.getPositionForView((View) v.getParent());
// Log.v(TAG, "item clicked, row %d", position);
}
};
}
You can use setTag()and getTag() method on your button.
Please look at the code below:
You have to change getItem method:
#Override
public Planning getItem(int arg0) {
return planArraylist.get(arg0);
}
Update your getView method:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
...
Button btn_save =(Button)convertView.findViewById(R.id.button1);
btn_save.setTag(position);
...
}
private OnClickListener ButtonClickListener = new OnClickListener() {
#Override
public void onClick(View v) {
final int position = (int)v.getTag();
Planning planning = getItem(position);
yourDatabaseHelper. getRuntimeExceptionDao(Planning.class).createOrUpdate(planning);
}
};
One more thing. You should implement ViewHolder please read about this pattern, and the best solution for you is use RecyclerView, getting position is already implemented there in RecyclerView.ViewHolder.

Cannot get gridview child at index

I am using a baseadapter to add items in the gridview, I do this in 'onclickevent of alistviewrow. Data is collected and passed to the adapter inarraylist` of custom object.
This is how I am doing it:
#Override
public void onClick(View arg0) {
List<GVShow> lstGVShow = new ArrayList<GVShow>();
//code to construct lstGVShow here..
FragmentTvGuideMain.gridView.setAdapter(new GridViewAdapter(
FragmentTvGuideMain.context.getApplicationContext(),
lstGVShow)); //FragmentTvGuideMain.context = getActivity() in Fragmentactivity
This is my gridviewadapter:
public class GridViewAdapter extends BaseAdapter {
private Context context;
private final List lstGVShow;
public GridViewAdapter(Context context, List<GVShow> lstGVShow) {
this.context = context;
this.lstGVShow = lstGVShow;
}
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View gridView;
if (convertView == null) {
gridView = convertView;//new View(context);
gridView = inflater.inflate(R.layout.gridview_tile_layout,parent, false);
TextView txtShowName = (TextView) gridView.findViewById(R.id.ShowTitle);
TextView txtShowDuration = (TextView) gridView.findViewById(R.id.ShowTime);
ImageButton imgBtnShow = (ImageButton) gridView.findViewById(R.id.image);
GVShow show = lstGVShow.get(position);
txtShowName.setText(show.getShowName());
ImageLoader.getInstance().displayImage(show.getShowImage(), imgBtnShow);
} else {
gridView = (View) convertView;
}
return gridView;
}
#Override
public int getCount() {
return lstGVShow.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
}
This is how I get the child from the gridview and it gives an NPE:
View rlNowPlaying = FragmentTvGuideMain.gridView.getChildAt(0); //done after setting the adapter
FragmentTvGuideMain.gridView.getCount(); //returns the correct number of views added in the gridview
It seems to me like some sort of a non-blocking call to set the views in baseadapter of the gridview. How do I go working around this?

Categories

Resources