Button's click in listiview not working properly - android

In my listview i set two buttons and one edittext but it is not working properly,the view of my buttons and edittext in listview is look like this
Button1 Edittext Button2
in my edittext i set 1,and Button1 is for decrement or minus and Button2 for increment or plus,but the issue is in every listitem it is not working properly,if i have three items in my listview,and if i increment in first item the operation is performing in third item,,
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View rootView = inflater.inflate(R.layout.list_view_addtocart, container, false);
totvalues=(TextView)rootView.findViewById(R.id.totaldisp);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
edtcopupon=(EditText)rootView.findViewById(R.id.edt_coupon);
btn_applycoupon=(Button)rootView.findViewById(R.id.aplycoupoon);
btn_applycoupon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
list=(ListView)rootView.findViewById(R.id.list_addtocart);
plcordr=(Button)rootView.findViewById(R.id.plcordr);
plcordr.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Placeorder tf = new Placeorder();
Bundle bundle = new Bundle();
tf.setArguments(bundle);
android.app.FragmentManager fm = getActivity().getFragmentManager();
android.app.FragmentTransaction ft = fm.beginTransaction();
ft.replace(R.id.container_body, tf);
ft.setTransition(android.support.v4.app.FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
ft.addToBackStack(null);
ft.commit();
}
});
ArrayList<ContactListItems> contactList = new ArrayList<ContactListItems>();
contactList.clear();
String query = "SELECT * FROM PHONE_CONTACTS ";
Cursor c1 = SqlHandler.selectQuery(query);
if (c1 != null & c1.getCount() != 0) {
if (c1.moveToNext()) {
do {
contactListItems = new ContactListItems();
contactListItems.setSlno(c1.getString(c1
.getColumnIndex("slno")));
contactListItems.setName(c1.getString(c1
.getColumnIndex("name")));
contactListItems.setPhone(c1.getString(c1
.getColumnIndex("phone")));
contactListItems.setSizes(c1.getString(c1
.getColumnIndex("sizes")));
contactListItems.setQtys(c1.getString(c1
.getColumnIndex("qtys")));
contactList.add(contactListItems);
} while (c1.moveToNext());
}
}
c1.close();
contactListAdapter = new ContactListAdapter(getActivity(), contactList);
list.setAdapter(contactListAdapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
}
});
return rootView;
}
public class ContactListAdapter extends BaseAdapter {
Context context;
ViewHolder holder;
ArrayList<ContactListItems> contactList;
String dollars = "\u0024";
public ContactListAdapter(Context context, ArrayList<ContactListItems> list) {
this.context = context;
contactList = list;
}
#Override
public int getCount() {
return contactList.size();
}
#Override
public Object getItem(int position) {
return contactList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(getActivity()).inflate(R.layout.list_item_addtocart, null);
holder.propic = (ImageView) convertView.findViewById(R.id.propicaccept);
holder.tvSlNo = (TextView) convertView.findViewById(R.id.txt_size);
holder.tvName = (TextView) convertView.findViewById(R.id.proprice_addtocart);
holder.tvPhone = (TextView) convertView.findViewById(R.id.proname_addtocart);
holder.tvsizes = (TextView) convertView.findViewById(R.id.txt_sizes);
holder._decrease = (Button)convertView.findViewById(R.id.minuss_addtocart);
holder.mBTIncrement = (Button)convertView.findViewById(R.id.plus_addtocart);
holder._value = (EditText)convertView.findViewById(R.id.edt_procount_addtocart);
holder.mBTIncrement.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//increment();
int mValue = Integer.parseInt(holder._value.getText().toString());
mValue++;
quntity++;
tots = pric * quntity;
System.out.println("INCRESE VALUES" + tots);
totvalues.setText(String.valueOf(tots));
holder._value.setText("" + mValue);
}
});
holder._decrease.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//decrement();
int mValue = Integer.parseInt(holder._value.getText().toString());
mValue--;
quntity--;
tots = pric * quntity;
System.out.println("INCRESE VALUES" + tots);
totvalues.setText(String.valueOf(tots));
if (mValue < 0) {
System.out.println("not valid");
holder._decrease.setEnabled(false);
} else {
holder._value.setText("" + mValue);
}
}
});
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.tvName.setText(dollars+contactListItems.getName());
holder.tvPhone.setText(contactListItems.getPhone());
holder.tvsizes.setText(contactListItems.getSizes());
holder._value.setText(contactListItems.getQtys());
quntity=Float.parseFloat(contactListItems.getQtys());
pric=Float.parseFloat(contactListItems.getName());
tots=pric*quntity;
totvalues.setText(String.valueOf(tots));
System.out.println("QTYSSS>>" + quntity);
System.out.println("PRICCC>>" + pric);
// float aditya=+tots;
System.out.println("TOTTTT>>" + tots);
//aQuery.id(holder.propic).image(listData.get(position).get(TAG_IMAGE),true,true,0,R.drawable.ic_launcher);
return convertView;
}
class ViewHolder{
ImageView propic;
TextView tvSlNo;
TextView tvName;
TextView tvPhone;
Button mBTIncrement;
TextView tvsizes;
Button _decrease;
public EditText _value;
}
}
XML
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/rectback"
>
<ImageView
android:layout_width="70dp"
android:layout_height="100dp"
android:id="#+id/img_addtocart"
android:src="#drawable/productfirst"
/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/relfirsrt"
android:layout_toRightOf="#+id/img_addtocart"
android:layout_above="#+id/relativeLayout"
android:layout_alignParentTop="true">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/proname_addtocart"
android:textAppearance="?android:attr/textAppearanceMedium"
android:maxLength="13"
android:textColor="#android:color/black"
/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/txt_size"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/txt_sizes"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/img_addtocart"
android:layout_toRightOf="#+id/img_addtocart"
android:layout_toEndOf="#+id/img_addtocart"
android:id="#+id/relativeLayout">
<Button
android:layout_width="40dp"
android:layout_height="29dp"
android:id="#+id/minuss_addtocart"
android:textAppearance="?android:attr/textAppearanceLarge"
android:background="#drawable/minusbox"
android:layout_alignParentTop="true"
android:layout_toLeftOf="#+id/edt_procount_addtocart"
android:layout_toStartOf="#+id/edt_procount_addtocart" />
<EditText
android:layout_width="40dp"
android:layout_height="29dp"
android:id="#+id/edt_procount_addtocart"
android:textAppearance="?android:attr/textAppearanceLarge"
android:background="#drawable/inputbox"
android:inputType="number"
android:gravity="center"
android:text="0"
android:layout_alignParentTop="true"
android:layout_toLeftOf="#+id/plus_addtocart"
android:layout_toStartOf="#+id/plus_addtocart" />
<Button
android:layout_width="40dp"
android:layout_height="29dp"
android:id="#+id/plus_addtocart"
android:textAppearance="?android:attr/textAppearanceLarge"
android:background="#drawable/addbox"
android:layout_alignParentTop="true"
android:focusable="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/proprice_addtocart"
android:gravity="center_vertical"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>
</RelativeLayout>

Write your onClick listener and tag assigning code outside the if-else block.
if (convertView == null) {
}
else {
}
holder.position = position;
holder.mBTIncrement.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//increment();
int mValue = Integer.parseInt(holder._value.getText().toString());
mValue++;
quntity++;
tots = pric * quntity;
System.out.println("INCRESE VALUES" + tots);
totvalues.setText(String.valueOf(tots));
holder._value.setText("" + mValue);
}
});
holder._decrease.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//decrement();
int mValue = Integer.parseInt(holder._value.getText().toString());
mValue--;
quntity--;
tots = pric * quntity;
System.out.println("INCRESE VALUES" + tots);
totvalues.setText(String.valueOf(tots));
if (mValue < 0) {
System.out.println("not valid");
holder._decrease.setEnabled(false);
} else {
holder._value.setText("" + mValue);
}
}
});

You need to base your logic on the position of the click, because the adapter may refresh itself after the click and change the position;
public class ContactListAdapter extends BaseAdapter {
Context context;
ViewHolder holder;
ArrayList<ContactListItems> contactList;
ArrayList<Integer> values;
String dollars = "\u0024";
public ContactListAdapter(Context context, ArrayList<ContactListItems> list) {
this.context = context;
contactList = list;
values = new ArrayList<>();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
holder = new ViewHolder();
values.add(contactListItems.getQtys());
convertView = LayoutInflater.from(getActivity()).inflate(R.layout.list_item_addtocart, null);
holder.propic = (ImageView) convertView.findViewById(R.id.propicaccept);
holder.tvSlNo = (TextView) convertView.findViewById(R.id.txt_size);
holder.tvName = (TextView) convertView.findViewById(R.id.proprice_addtocart);
holder.tvPhone = (TextView) convertView.findViewById(R.id.proname_addtocart);
holder.tvsizes = (TextView) convertView.findViewById(R.id.txt_sizes);
holder._decrease = (Button)convertView.findViewById(R.id.minuss_addtocart);
holder.mBTIncrement = (Button)convertView.findViewById(R.id.plus_addtocart);
holder._value = (EditText)convertView.findViewById(R.id.edt_procount_addtocart);
holder.mBTIncrement.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int position = holder.position;
int mValue = Integer.parseInt(holder._value.getText().toString());
mValue++;
quntity++;
tots = pric * quntity;
System.out.println("INCRESE VALUES" + tots);
totvalues.setText(String.valueOf(tots));
values.set(position, mValue);
}
});
holder._decrease.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int position = holder.position;
int mValue = Integer.parseInt(holder._value.getText().toString());
mValue--;
quntity--;
tots = pric * quntity;
System.out.println("INCRESE VALUES" + tots);
totvalues.setText(String.valueOf(tots));
values.set(position, mValue);
}
});
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.position = position;
holder.tvName.setText(dollars+contactListItems.getName());
holder.tvPhone.setText(contactListItems.getPhone());
holder.tvsizes.setText(contactListItems.getSizes());
int value = values.get(position);
if (value < 0) {
holder._decrease.setEnabled(false);
} else {
holder._value.setText("" + mValue);
}
quntity=Float.parseFloat(contactListItems.getQtys());
pric=Float.parseFloat(contactListItems.getName());
tots=pric*quntity;
totvalues.setText(String.valueOf(tots));
System.out.println("QTYSSS>>" + quntity);
System.out.println("PRICCC>>" + pric);
// float aditya=+tots;
System.out.println("TOTTTT>>" + tots);
//aQuery.id(holder.propic).image(listData.get(position).get(TAG_IMAGE),true,true,0,R.drawable.ic_launcher);
return convertView;
}
class ViewHolder{
int position;
ImageView propic;
TextView tvSlNo;
TextView tvName;
TextView tvPhone;
Button mBTIncrement;
TextView tvsizes;
Button _decrease;
public EditText _value;
}
}

Try implementing adapter like below
private Context context;
private List<ContactListItems> items;
/**
* #param context
* #param groupList
*/
public TestListAdapter(Context context, List<ContactListItems> items) {
this.context = context;
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.li_plus_minus, parent, false);
holder = new ViewHolder();
holder.plus = (Button) convertView.findViewById(R.id.plus);
holder.minus = (Button) convertView.findViewById(R.id.minus);
holder.et = (EditText) convertView.findViewById(R.id.editText);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
ContactListItems item = items.get(position);
holder.et.setText(String.valueOf(item.value));
holder.plus.setOnClickListener(new ClickListener(item));
holder.minus.setOnClickListener(new ClickListener(item));
return convertView;
}
class ClickListener implements View.OnClickListener {
private ContactListItems item;
public ClickListener(ContactListItems item) {
this.item = item;
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.minus) {
item.value--;
} else if (v.getId() == R.id.plus) {
item.value++;
}
notifyDataSetChanged();
}
}
class ViewHolder {
Button plus, minus;
EditText et;
}
Hope this helps

Add this line in your Customise view parent layout.
android:descendantFocusability="blocksDescendants"

Related

Android ListView with Image, text and button

I am trying to build a listview which contains outlet address in 5 lines,along with a status indicator image and a button. The following is the functionality I am trying to build.
When the list text is clicked - I want to open a activity.
When the button (COMP) is clicked - I want to open a different activity.
The image (tickmark) is a status indicator to inform the user whether the activity in a outlet is complete or not.
The list is populated from a SqliteDatabase. On clicking the button, I want to take the reference of the outlet and show different attributes of the outlet.
How do I integrate the button into the list view.
I have written the following code so far:
LISTVIEW.XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="3dp"
android:background="#FFFFFF"
android:layout_marginLeft="2dp"
android:layout_marginBottom="2dp"
android:descendantFocusability="blocksDescendants"
>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical">
<ImageView
android:id="#+id/imageViewFlag"
android:layout_rowSpan="2"
android:layout_width="25dp"
android:layout_height="25dp"
android:scaleType="fitXY"
android:layout_marginTop="20dp"
android:foregroundGravity="center"
android:layout_gravity="center"
android:background="#drawable/compliance_foreground"
android:layout_row="0"
android:layout_column="0" />
<Button
android:id="#+id/complianceButton"
android:layout_width="70dp"
android:layout_height="35dp"
android:text="COMP"
android:textSize="12sp"
></Button>
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_marginLeft="5dp"
>
<TextView
android:id="#+id/tvOutletNamealt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Outlet :"
android:textSize="15sp"
android:layout_marginLeft="2dp"
android:layout_marginTop="2dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#04031A"
android:textAllCaps="true"
android:layout_columnWeight="1"
android:layout_row="0"
android:layout_column="1" />
<TextView
android:id="#+id/tvOutletAddress1alt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Address1 :"
android:textSize="12sp"
android:layout_marginLeft="2dp"
android:layout_marginTop="2dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#000000"
android:layout_columnWeight="1"
android:layout_row="1"
android:layout_column="1" />
<TextView
android:id="#+id/tvOutletAddress2alt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Address2 :"
android:textSize="12sp"
android:layout_marginLeft="2dp"
android:layout_marginTop="2dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#000000"
android:layout_columnWeight="1"
android:layout_row="2"
android:layout_column="1" />
<TextView
android:id="#+id/tvOutletCityalt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="City :"
android:textSize="12sp"
android:layout_marginLeft="2dp"
android:layout_marginTop="2dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#000000"
android:layout_columnWeight="1"
android:layout_row="3"
android:layout_column="1" />
<TextView
android:id="#+id/tvOutletPhonealt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="PhoneNumber :"
android:textSize="13sp"
android:layout_marginLeft="2dp"
android:layout_marginTop="2dp"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#000000"
android:layout_columnWeight="1"
android:layout_row="4"
android:layout_column="1" />
</LinearLayout>
</LinearLayout>
MainActivity.java
public class show_outlets_alt extends AppCompatActivity {
SQLiteHelper sqLiteHelper;
SQLiteDatabase sqLiteDatabase;
Cursor cursor;
AltOutletAdapter listAdapterOutlets ;
String lati;
String longi;
String projectName;
String usrname;
Button cButton;
ListView LISTVIEWOUTLETS;
ArrayList<String> Id_Array;
ArrayList<String> OutletName_Array;
ArrayList<String> OutletAddress1_Array;
ArrayList<String> OutletAddress2_Array;
ArrayList<String> City_Array;
ArrayList<String> Phone_Array;
ArrayList<String> ListViewClickItemArrayOutlets = new ArrayList<String>();
private String projectID;
ImageView imageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
setContentView( R.layout.activity_show_outlets_alt );
// Set toolbar for this screen
Toolbar sectoolbar = (Toolbar) findViewById( R.id.secondary_toolbar );
sectoolbar.setTitle("");
sectoolbar.setBackground(new ColorDrawable(getResources().getColor(R.color.primary_welcome_color)));
TextView main_title = (TextView) findViewById(R.id.secondary_toolbar_title);
main_title.setText("PROJECT LOCATIONS");
main_title.setTextColor( this.getResources().getColor( R.color.white ) );
setSupportActionBar( sectoolbar );
usrname = SaveSharedPreference.getUserName( show_outlets_alt.this );
projectID = SaveSharedPreference.getProjName( show_outlets_alt.this );
LISTVIEWOUTLETS = this.findViewById( R.id.listView2alt );
imageView = this.findViewById( R.id.imageViewFlag );
cButton = findViewById( R.id.complianceButton );
Id_Array = new ArrayList<>();
OutletName_Array = new ArrayList<>();
OutletAddress1_Array = new ArrayList<>();
OutletAddress2_Array = new ArrayList<>();
City_Array = new ArrayList<>();
Phone_Array = new ArrayList<>();
sqLiteHelper = new SQLiteHelper(this);
LISTVIEWOUTLETS.setOnItemClickListener( new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
projectName = SaveSharedPreference.getProjName( show_outlets_alt.this );
String outletName = ListViewClickItemArrayOutlets.get(position).toString();
SaveSharedPreference.setOutletName( getApplicationContext(),outletName );
Intent intent = new Intent(getApplicationContext(), ShowOutletParams.class);
startActivityForResult( intent,1 );
}
} );
} //end of oncreate
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult( requestCode, resultCode, data );
if (resultCode == RESULT_OK) {
Intent refresh = new Intent( this, ShowDataActivity.class );
startActivityForResult(refresh,1);
this.finish();
}
}
#Override
protected void onResume() {
ShowSQLiteOutletdata();
super.onResume();
}
private void ShowSQLiteOutletdata() {
sqLiteDatabase = sqLiteHelper.getWritableDatabase();
projectID = SaveSharedPreference.getProjName( show_outlets_alt.this );
cursor = sqLiteDatabase.rawQuery("SELECT * FROM "+SQLiteHelper.TABLE_NAME1+" where pid = (select projectId from "+SQLiteHelper.TABLE_NAME+ " where ProjectName = '"+projectID+"'"+") and Status=1;", null);
Id_Array.clear();
OutletName_Array.clear();
OutletAddress1_Array.clear();
OutletAddress2_Array.clear();
City_Array.clear();
Phone_Array.clear();
if (cursor != null && cursor.getCount() > 0) {
if (cursor.moveToFirst()) {
do {
Id_Array.add(cursor.getString(cursor.getColumnIndex(SQLiteHelper.Table1_Column_ID)));
ListViewClickItemArrayOutlets.add(cursor.getString(cursor.getColumnIndex(SQLiteHelper.Table1_Column_OutletName)));
OutletName_Array.add(cursor.getString(cursor.getColumnIndex(SQLiteHelper.Table1_Column_OutletName)));
OutletAddress1_Array.add(cursor.getString(cursor.getColumnIndex(SQLiteHelper.Table1_Column_outletAddress1)));
OutletAddress2_Array.add(cursor.getString(cursor.getColumnIndex(SQLiteHelper.Table1_Column_outletAddress2)));
City_Array.add(cursor.getString(cursor.getColumnIndex(SQLiteHelper.Table1_Column_city)));
Phone_Array.add(cursor.getString(cursor.getColumnIndex(SQLiteHelper.Table1_Column_phone)));
} while (cursor.moveToNext());
}
}
listAdapterOutlets = new AltOutletAdapter(show_outlets_alt.this,
Id_Array,
OutletName_Array,
OutletAddress1_Array,
OutletAddress2_Array,
City_Array,
Phone_Array
);
LISTVIEWOUTLETS.setAdapter(listAdapterOutlets);
cursor.close();
} //end of ShowSqliteOutletData
#Override
public void onBackPressed() {
super.onBackPressed();
Intent backIntent = new Intent(getApplicationContext(), ShowDataActivity.class);
startActivity(backIntent);
}
}//end of public class
AltOutletAdapter.java
public class AltOutletAdapter extends BaseAdapter {
Context context;
ArrayList<String> ID;
ArrayList<String> O_Name;
ArrayList<String> O_Address1;
ArrayList<String> O_Address2;
ArrayList<String> City;
ArrayList<String> Phone;
ArrayList<String> iButton;
public AltOutletAdapter(Context context, ArrayList<String> ID, ArrayList<String> o_Name, ArrayList<String> o_Address1, ArrayList<String> o_Address2, ArrayList<String> city, ArrayList<String> phone) {
this.context = context;
this.ID = ID;
O_Name = o_Name;
O_Address1 = o_Address1;
O_Address2 = o_Address2;
City = city;
Phone = phone;
}
#Override
public int getCount() {
return ID.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View child, ViewGroup parent) {
AltOutletAdapter.Holder holder;
LayoutInflater layoutInflater;
if (child == null) {
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
child = layoutInflater.inflate(R.layout.alt_list_view, null);
holder = new AltOutletAdapter.Holder();
holder.O_Name = (TextView) child.findViewById(R.id.tvOutletNamealt);
holder.O_Address1 = (TextView) child.findViewById(R.id.tvOutletAddress1alt);
holder.O_Address2 = (TextView) child.findViewById(R.id.tvOutletAddress2alt);
holder.City = (TextView) child.findViewById(R.id.tvOutletCityalt);
holder.Phone = (TextView) child.findViewById(R.id.tvOutletPhonealt);
child.setTag(holder);
} else {
holder = (AltOutletAdapter.Holder) child.getTag();
}
holder.O_Name.setText(O_Name.get(position));
holder.O_Address1.setText(O_Address1.get(position));
holder.O_Address2.setText(O_Address2.get(position));
holder.City.setText(City.get(position));
holder.Phone.setText(Phone.get(position));
return child;
}
private class Holder {
TextView O_Name;
TextView O_Address1;
TextView O_Address2;
TextView City;
TextView Phone;
Button iButton;
ImageView imageView;
}
}
first I have question.
why don't you make Model for Items?
Anyway if you want to make click event by element, just add click listener in your adapter.
so Example is here
add id in your whole layout.
( android:id="#+id/layout" )
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="3dp"
android:background="#FFFFFF"
android:layout_marginLeft="2dp"
android:layout_marginBottom="2dp"
android:descendantFocusability="blocksDescendants">
...
add click listener in your adapter
public class AltOutletAdapter extends BaseAdapter {
Context context;
ArrayList<String> ID;
ArrayList<String> O_Name;
ArrayList<String> O_Address1;
ArrayList<String> O_Address2;
ArrayList<String> City;
ArrayList<String> Phone;
ArrayList<String> iButton;
public LinearLayout linearLayout;
public AltOutletClickListener altOutletClickListener;
public AltOutletAdapter(Context context, ArrayList<String> ID, ArrayList<String> o_Name, ArrayList<String> o_Address1, ArrayList<String> o_Address2, ArrayList<String> city, ArrayList<String> phone, AltOutletClickListener listener) {
this.context = context;
this.ID = ID;
O_Name = o_Name;
O_Address1 = o_Address1;
O_Address2 = o_Address2;
City = city;
Phone = phone;
altOutletClickListener = listener;
}
#Override
public int getCount() {
return ID.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View child, ViewGroup parent) {
AltOutletAdapter.Holder holder;
LayoutInflater layoutInflater;
if (child == null) {
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
child = layoutInflater.inflate(R.layout.alt_list_view, null);
holder = new AltOutletAdapter.Holder();
holder.O_Name = (TextView) child.findViewById(R.id.tvOutletNamealt);
holder.O_Address1 = (TextView) child.findViewById(R.id.tvOutletAddress1alt);
holder.O_Address2 = (TextView) child.findViewById(R.id.tvOutletAddress2alt);
holder.City = (TextView) child.findViewById(R.id.tvOutletCityalt);
holder.Phone = (TextView) child.findViewById(R.id.tvOutletPhonealt);
holder.linearLayout = (LinearLayout) child.findViewById(R.id.layout);
holder.iButton = (Button) child.findViewById(R.id.complianceButton);
child.setTag(holder);
} else {
holder = (AltOutletAdapter.Holder) child.getTag();
}
holder.O_Name.setText(O_Name.get(position));
holder.O_Address1.setText(O_Address1.get(position));
holder.O_Address2.setText(O_Address2.get(position));
holder.City.setText(City.get(position));
holder.Phone.setText(Phone.get(position));
holder.linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
altOutletClickListener.itemClickListener(v, position);
}
});
holder.iButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
altOutletClickListener.imageClickListener(v, position);
}
});
return child;
}
private class Holder {
TextView O_Name;
TextView O_Address1;
TextView O_Address2;
TextView City;
TextView Phone;
Button iButton;
ImageView imageView;
LinearLayout linearLayout;
}
public interface AltOutletClickListener {
void itemClickListener(View v, int position);
void imageClickListener(View v, int position);
}
}
when you call adapter in java, add click event as params.
ArrayList<String> test = new ArrayList<>();
AltOutletAdapter altOutletAdapter = new AltOutletAdapter(MainActivity.this, test, test, test, test, test, test, new AltOutletAdapter.AltOutletClickListener() {
#Override
public void itemClickListener(View v, int position) {
// when click layout
}
#Override
public void imageClickListener(View v, int position) {
// when click button
}
});
I just tested and use this.
But I think make Model is better.
ArrayList<String> test = new ArrayList<>();
ArrayList<Model> test = new ArrayList<>(); // it is better
**UPDATE : make Model **
simply, I make your Model Example.
make Model file.
public class AltOutlet {
private String name;
private String address1;
private String address2;
private String city;
private String phone;
public AltOutlet(String name, String address1, String address2, String city, String phone) {
this.name = name;
this.address1 = address1;
this.address2 = address2;
this.city = city;
this.phone = phone;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress1() {
return address1;
}
public void setAddress1(String address1) {
this.address1 = address1;
}
public String getAddress2() {
return address2;
}
public void setAddress2(String address2) {
this.address2 = address2;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
change your adapter
public class AltOutletAdapter extends BaseAdapter {
Context context;
ArrayList<AltOutlet> altOutletArrayList;
public LinearLayout linearLayout;
public AltOutletClickListener altOutletClickListener;
public AltOutletAdapter(Context context, ArrayList<AltOutlet> altOutletList, AltOutletClickListener listener) {
this.context = context;
altOutletArrayList = altOutletList;
altOutletClickListener = listener;
}
#Override
public int getCount() {
return altOutletArrayList.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View child, ViewGroup parent) {
AltOutletAdapter.Holder holder;
LayoutInflater layoutInflater;
if (child == null) {
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
child = layoutInflater.inflate(R.layout.alt_list_view, null);
holder = new AltOutletAdapter.Holder();
holder.O_Name = (TextView) child.findViewById(R.id.tvOutletNamealt);
holder.O_Address1 = (TextView) child.findViewById(R.id.tvOutletAddress1alt);
holder.O_Address2 = (TextView) child.findViewById(R.id.tvOutletAddress2alt);
holder.City = (TextView) child.findViewById(R.id.tvOutletCityalt);
holder.Phone = (TextView) child.findViewById(R.id.tvOutletPhonealt);
holder.linearLayout = (LinearLayout) child.findViewById(R.id.layout);
holder.iButton = (Button) child.findViewById(R.id.complianceButton);
child.setTag(holder);
} else {
holder = (AltOutletAdapter.Holder) child.getTag();
}
holder.O_Name.setText(altOutletArrayList.get(position).getName());
holder.O_Address1.setText(altOutletArrayList.get(position).getAddress1());
holder.O_Address2.setText(altOutletArrayList.get(position).getAddress2());
holder.City.setText(altOutletArrayList.get(position).getCity());
holder.Phone.setText(altOutletArrayList.get(position).getPhone());
holder.linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
altOutletClickListener.itemClickListener(v, position);
}
});
holder.iButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
altOutletClickListener.imageClickListener(v, position);
}
});
return child;
}
private class Holder {
TextView O_Name;
TextView O_Address1;
TextView O_Address2;
TextView City;
TextView Phone;
Button iButton;
ImageView imageView;
LinearLayout linearLayout;
}
public interface AltOutletClickListener {
void itemClickListener(View v, int position);
void imageClickListener(View v, int position);
}
}
when you add item in java file, use Model
AltOutlet altOutlet = new AltOutlet("test", "address1", "address2", "city", "phone");
altOutlets.add(altOutlet);
AltOutletAdapter altOutletAdapter = new AltOutletAdapter(MainActivity.this, altOutlets, new AltOutletAdapter.AltOutletClickListener() {
#Override
public void itemClickListener(View v, int position) {
// when click layout
}
#Override
public void imageClickListener(View v, int position) {
// when click button
}
});

mproduct.remove(position) or notifyDataSetChange() does not work inside getView method

I have checked most of the places but i could not get the precise answer for this question.
problem in function : getView
What is the problem : When if condition gets true,
mproduct.remove((position));
notifyDataSetChanged();
both statement suppose to work.
// here mproduct is object of ArrayList;
If i write Log.e(); It displays promt message.
Thanks in advance.
{
public class DataAdapterCheckOut extends BaseAdapter {
Context context;
ArrayList<CheckOutProduct> mproduct;
public DataAdapterCheckOut(Context context, ArrayList<CheckOutProduct>
product){
// super(context, R.layout.activity_list_product, product);
this.context=context;
this.mproduct=product;
}
public class Holder{
TextView nameFV, mrpFV, our_priceFV, weightFv, unitFV, countFV;
ImageView pic;
int countTemp=1,mrp=0,ourPrice=0;
String name;
Button btnAdd, btnSubstract, btnAddCart;
}
#Override
public int getCount() {
return mproduct.size();
}
#Override
public Object getItem(int position) {
return mproduct.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final CheckOutProduct checkOutProduct = mproduct.get(position);
// Check if an existing view is being reused, otherwise inflate the view
SharedPreferences prefs = context.getSharedPreferences("MNA",
Context.MODE_PRIVATE);
String personalEmail = prefs.getString("personalEmail", null);
String mobTemp = prefs.getString("MNAF", null);
final Holder viewHolder; // view lookup cache stored in tag
if (convertView == null) {
viewHolder = new Holder();
LayoutInflater inflater = LayoutInflater.from(context);
convertView = inflater.inflate(R.layout.activity_list_product,
parent, false);
viewHolder.nameFV = (TextView)
convertView.findViewById(R.id.txtNameViewer);
//viewHolder.idFV = (TextView)
convertView.findViewById(R.id.txtIdViewer);
viewHolder.mrpFV = (TextView)
convertView.findViewById(R.id.txtMrpViewer);
viewHolder.our_priceFV = (TextView)
convertView.findViewById(R.id.txtOurPriceViewer);
viewHolder.weightFv = (TextView)
convertView.findViewById(R.id.txtWeightViewer);
viewHolder.unitFV = (TextView)
convertView.findViewById(R.id.txtUnitViewer);
viewHolder.countFV = (TextView)
convertView.findViewById(R.id.txtViewProductCount);
viewHolder.pic = (ImageView)
convertView.findViewById(R.id.imgView);
viewHolder.btnAdd = (Button)
convertView.findViewById(R.id.buttonAdd);
viewHolder.btnSubstract = (Button)
convertView.findViewById(R.id.buttonSubstract);
viewHolder.btnAddCart = (Button)
convertView.findViewById(R.id.buttonAddCart);
convertView.setTag(viewHolder);
} else {
viewHolder = (Holder) convertView.getTag();
}
viewHolder.nameFV.setText(checkOutProduct.get_name());
viewHolder.name = checkOutProduct.get_name();
viewHolder.mrpFV.setText("MRP : " +
checkOutProduct.getMrp());
viewHolder.mrp = checkOutProduct.getMrp();
viewHolder.our_priceFV.setText("Our Price : " +
checkOutProduct.getOurPrice());
viewHolder.ourPrice = checkOutProduct.getOurPrice();
viewHolder.weightFv.setText(checkOutProduct.getWeight());
viewHolder.unitFV.setText(" " + checkOutProduct.getUnit());
viewHolder.pic.setImageBitmap(convertToBitmap(checkOutProduct.getImage()));
viewHolder.countFV.setText("" +
checkOutProduct.get_quantity());
viewHolder.countTemp = checkOutProduct.get_quantity();
viewHolder.btnAdd.setOnClickListener(new
View.OnClickListener() {
#Override
public void onClick(View v) {
viewHolder.countTemp++;
viewHolder.countFV.setText("" +
viewHolder.countTemp);
}
});
viewHolder.btnSubstract.setOnClickListener(new
View.OnClickListener() {
#Override
public void onClick(View v) {
viewHolder.countTemp--;
if (viewHolder.countTemp >= 1)
viewHolder.countFV.setText("" +
viewHolder.countTemp);
else {
Toast.makeText(context, "Sorry Item Count at
least 1", Toast.LENGTH_LONG).show();
viewHolder.countTemp = 1;
}
}
});
viewHolder.btnAddCart.setOnClickListener(new
View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e("B", "Added into Cart");
SharedPreferences prefs =
context.getSharedPreferences("MNA", Context.MODE_PRIVATE);
String personalEmail =
prefs.getString("personalEmail", null);
CheckOutDBHelper checkOutDBHelper1 = new
CheckOutDBHelper(context);
checkOutDBHelper1.addCheckOutInformation(new
CheckOutProduct(personalEmail, checkOutProduct.get_name(),
checkOutProduct.getID(), checkOutProduct.getMrp(),
checkOutProduct.getOurPrice(), checkOutProduct.getWeight(),
checkOutProduct.getUnit(), checkOutProduct.getImage(),
viewHolder.countTemp));
}
});
UserDBHelper userDBHelper = new UserDBHelper(context);
if(personalEmail!=null&&!personalEmail.equals(checkOutProduct.get_gmail()))
{
mproduct.remove(position);
notifyDataSetChanged();
}
if (mobTemp!=null&&!userDBHelper.getEmailId(mobTemp).equals(checkOutProduct.get_gmail())){
mproduct.remove((`enter code here`position));
notifyDataSetChanged();
enter code here
}
return convertView;
}
//get bitmap image from byte array
private Bitmap convertToBitmap(byte[] b){
return BitmapFactory.decodeByteArray(b, 0, b.length);
}
}
}

Null Pointer Exception at Imageview in Custom List View

I have a custom list view with a TextView and three ImageViews. On click of image view I want to start a new activity and pass the data of specific position to next activity. But I am getting null pointer exception.
I have use this for refernce http://jmsliu.com/2444/click-button-in-listview-and-get-item-position.html
Here is my code. This is main Activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_employees);
toolbar = (Toolbar) findViewById(R.id.app_bar);
toolbar.setTitle("Manage Employees");
nPregress = (ProgressBar) findViewById(R.id.toolbar_progress_bar);
nPregress.setVisibility(View.GONE);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
mainList = (ListView) findViewById(R.id.manageemployeeList);
employee1 = new ArrayList<Pojo>();
tii = new ArrayList<String>();
SharedPreferences prefs = getSharedPreferences("MyPref4", MODE_PRIVATE);
Set<String> set1 = prefs.getStringSet("employeename", null);
if (set1 != null ) {
List<String> nameList = new ArrayList<String>(0);
nameList.addAll(set1);
for (int i = 0; i < set1.size(); i++) {
pojo = new Pojo();
pojo.setMgEmpName(nameList.get(i));
employee1.add(pojo);
Log.e("namemmee0", "" + nameList.get(i));
}
mainAdapter = new EmployeesAdapter(EmployeesActivity.this, employee1);
mainList.setAdapter(mainAdapter);
} else {
new NetCheck().execute();
}
new NetCheck().execute();
emp_edit = (ImageView) findViewById(R.id.imgedit);
emp_edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View parentRow = (View) v.getParent();
mainList = (ListView) parentRow.getParent();
final int position = mainList.getPositionForView(parentRow);
String emp_name = employee1.get(position).getMgEmpName().toString();
Intent i = new Intent(EmployeesActivity.this, EditEmployee.class);
i.putExtra("empname", emp_name);
startActivity(i);
}
});
}
I am getting exception at this line
emp_edit.setOnClickListener(new View.OnClickListener()
How can i do this? Please help me.
This is my Adapter. I have tried onClickListener in adpter also But i am not gtting proper data in next activity.. I get same value even if i select different list view items
public class EmployeesAdapter extends BaseAdapter {
TextView categoryName;
Pojo pojo;
private Context activity1;
ArrayList<Pojo> data1;
private ArrayList<Pojo> arraylist1 = null;
public static LayoutInflater inflater;
ImageView edit, delete, historyy;
String del_empid;
public EmployeesAdapter(Context ctx, ArrayList<Pojo> employee1) {
// TODO Auto-generated constructor stub
activity1 = ctx;
data1 = employee1;
inflater = (LayoutInflater) activity1
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.arraylist1 = new ArrayList<Pojo>();
this.arraylist1.addAll(data1);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return data1.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return data1.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v = convertView;
v = inflater.inflate(R.layout.manage_emp_list, parent, false);
pojo = data1.get(position);
categoryName = (TextView) v.findViewById(R.id.employeeName);
categoryName.setText(pojo.getMgEmpName());
edit = (ImageView) v.findViewById(R.id.imgedit);
delete = (ImageView) v.findViewById(R.id.imgdelete);
historyy = (ImageView) v.findViewById(R.id.imgHistory);
edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(activity1, EditEmployee.class);
intent.putExtra("empname", "" + pojo.getMgEmpName());
intent.putExtra("empmobile", "" + pojo.getMgEmpContact());
intent.putExtra("empemail", "" + pojo.getMgEmpEmail());
intent.putExtra("empappcost", "" + pojo.getMgEmpAppCost());
activity1.startActivity(intent);
}
});
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
del_empid = pojo.getMgEmp_id();
new NetCheck().execute();
}
});
historyy.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(activity1, MainActivity.class);
activity1.startActivity(intent);
}
});
return v;
}
manage_emp_list of the custom list view
<?xml version="1.0" encoding="utf-8"?>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Text"
android:id="#+id/employeeName"
android:textColor="#000000"
android:textSize="18dp"
android:padding="5dp"
android:layout_marginLeft="5dp"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imgdelete"
android:src="#drawable/delete32"
android:layout_marginRight="12dp"
android:layout_marginEnd="12dp"
android:layout_alignBottom="#+id/employeeName"
android:layout_toLeftOf="#+id/imgedit"
android:layout_toStartOf="#+id/imgedit"
android:clickable="true"
android:onClick="delete_empoyee"/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imgedit"
android:layout_marginRight="15dp"
android:layout_marginEnd="15dp"
android:src="#drawable/edit32"
android:layout_alignTop="#+id/imgdelete"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:clickable="true"
/>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/imgHistory"
android:src="#drawable/history32"
android:clickable="true"
android:onClick="employee_history"
android:layout_alignParentTop="true"
android:layout_toLeftOf="#+id/imgdelete"
android:layout_toStartOf="#+id/imgdelete"
/>
Try this, There may be position mismatch when store it locally
edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(activity1, EditEmployee.class);
intent.putExtra("empname", "" + data1.get(position).getMgEmpName());
intent.putExtra("empmobile", "" + data1.get(position).getMgEmpContact());
intent.putExtra("empemail", "" + data1.get(position).getMgEmpEmail());
intent.putExtra("empappcost", "" + data1.get(position).getMgEmpAppCost());
activity1.startActivity(intent);
}
});
Your getView() method should look like this in your adapter:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
pojo = data1.get(position);
ViewHolder holder;
if (pojo != null) {
if (convertView == null) {
convertView = mInflater.inflate(R.layout.manage_emp_list, parent, false);
holder = new ViewHolder(convertView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.categoryName.setText(pojo.getMgEmpName());
//holder.edit.setOnClickListener()...
//holder.delete.setOnclickListener()...
}
return convertView;
}
And add a static class in to your Adapter:
static class ViewHolder {
TextView categoryName;
ImageView edit;
ImageView delete;
ImageView historyy;
public ViewHolder(View view) {
categoryName = (TextView) v.findViewById(R.id.employeeName);
edit = (ImageView) v.findViewById(R.id.imgedit);
delete = (ImageView) v.findViewById(R.id.imgdelete);
historyy = (ImageView) v.findViewById(R.id.imgHistory);
}
}

ImageButton in GridView get click position?

I'm trying create a GridView with some ImageButtons but I can't make onClick of these ImageButtons. I want get these clicks to open other Activitys/Fragments but I can't get position of ImageButton to do it.
How could I get position of ImageButton to click ?
GridView
Adapter XML
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/llPrincipal">
<ImageButton
android:id="#+id/ibPlano"
android:layout_width="100dp"
android:layout_height="100dp"
android:scaleType="fitXY"
android:background="#00000000"
android:focusable="false"
/>
<TextView
android:id="#+id/tvPlano"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:gravity="center"
/>
</LinearLayout>
PrincipalFrag
public class PrincipalFrag extends Fragment implements View.OnClickListener, AdapterView.OnItemClickListener{
private List<Permissoes> permissoesTela = new ArrayList<Permissoes>();
private GridView gridView;
private PrincipalAdapter principalAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.principal_frag, container, false);
gridView = (GridView)view.findViewById(R.id.gridView);
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
principalAdapter = new PrincipalAdapter(getView().getContext(), getPermissoesTela());
gridView.setAdapter(principalAdapter);
}
#Override
public void onClick(View v) {
}
private List<Permissoes> getPermissoesTela(){
////agenda, despesa, enviar, alterar estoque bloqueados
Usuario usuario = KontroleConfigs.PESSOA;
//venda
Permissoes venda = new Permissoes();
venda.setVenda(usuario.getPlano().getPermissoes().getVenda());
//agenda
Permissoes agenda = new Permissoes();
agenda.setAgenda(usuario.getPlano().getPermissoes().getAgenda());
//cadastro
Permissoes cadastro = new Permissoes();
cadastro.setCadastro(1);
//despesas
Permissoes despesas = new Permissoes();
despesas.setLancamento_dispesas(usuario.getPlano().getPermissoes().getLancamento_dispesas());
//enviar
Permissoes enviar = new Permissoes();
enviar.setEnviar_relatorio_txt(usuario.getPlano().getPermissoes().getEnviar_relatorio_txt());
//meus dados
Permissoes meusDados = new Permissoes();
meusDados.setMeusDados(1);
//recebimentos pendentes
Permissoes recebimentosPendentes = new Permissoes();
recebimentosPendentes.setRecebimentos_pendentes(usuario.getPlano().getPermissoes().getRecebimentos_pendentes());
//entregas pendentes
Permissoes entregasPendentes = new Permissoes();
entregasPendentes.setEntregas_pendentes(usuario.getPlano().getPermissoes().getEntregas_pendentes());
//alterar estoque
Permissoes alterarEstoque = new Permissoes();
alterarEstoque.setAlterar_estoque(usuario.getPlano().getPermissoes().getAlterar_estoque());
permissoesTela.add(venda);
permissoesTela.add(agenda);
permissoesTela.add(cadastro);
permissoesTela.add(despesas);
permissoesTela.add(enviar);
permissoesTela.add(meusDados);
permissoesTela.add(recebimentosPendentes);
permissoesTela.add(entregasPendentes);
permissoesTela.add(alterarEstoque);
return permissoesTela;
}
#Override
public void onPause() {
super.onPause();
CustomVolleySingleton.getInstance().cancelPendingRequests(CustomVolleySingleton.TAG);
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.i("POSITION BUTTON IN GRID VIEW->", position + "");
}
}
PrincipalAdapter
public class PrincipalAdapter extends BaseAdapter {
private Context context;
private List<Permissoes> lista;
public PrincipalAdapter(Context context, List<Permissoes> lista) {
this.context = context;
this.lista = lista;
}
#Override
public int getCount() {
return lista.size();
}
#Override
public Object getItem(int position) {
return lista.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
Usuario usuario = KontroleConfigs.PESSOA;
if (convertView == null) {
viewHolder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.principal_adapter, parent, false);
viewHolder.llPrincipal = (LinearLayout) convertView.findViewById(R.id.llPrincipal);
viewHolder.ibPlano = (ImageButton) convertView.findViewById(R.id.ibPlano);
viewHolder.tvPlano = (TextView) convertView.findViewById(R.id.tvPlano);
convertView.setTag(viewHolder);
}else{
viewHolder = (ViewHolder)convertView.getTag();
}
//permissoes
Permissoes p = lista.get(position);
//plano lite
////agenda, despesa, enviar, alterar estoque bloqueados
if(usuario.getPlano().getNome().contains("Bronze Lite")){
if(p.getVenda() != null){
if(p.getVenda() > 0){
viewHolder.ibPlano.setImageResource(R.drawable.vendas);
viewHolder.ibPlano.setEnabled(true);
}else{
viewHolder.ibPlano.setImageResource(R.drawable.vendas_2);
viewHolder.ibPlano.setEnabled(false);
}
viewHolder.tvPlano.setText("Vendas");
}else if(p.getAgenda() != null){
if(p.getAgenda() > 0){
viewHolder.ibPlano.setImageResource(R.drawable.agenda);
viewHolder.ibPlano.setEnabled(true);
}else{
viewHolder.ibPlano.setImageResource(R.drawable.agenda_2);
viewHolder.ibPlano.setEnabled(false);
}
viewHolder.tvPlano.setText("Agendas");
}else if(p.getCadastro() != null){
if(p.getCadastro() > 0){
viewHolder.ibPlano.setImageResource(R.drawable.cadastro);
viewHolder.ibPlano.setEnabled(true);
}else{
viewHolder.ibPlano.setImageResource(R.drawable.cadastro_2);
viewHolder.ibPlano.setEnabled(false);
}
viewHolder.tvPlano.setText("Cadastro");
}else if(p.getLancamento_dispesas() != null){
if(p.getLancamento_dispesas() > 0){
viewHolder.ibPlano.setImageResource(R.drawable.despesas);
viewHolder.ibPlano.setEnabled(true);
}else{
viewHolder.ibPlano.setImageResource(R.drawable.despesas_2);
viewHolder.ibPlano.setEnabled(false);
}
viewHolder.tvPlano.setText("Despesas");
}else if(p.getEnviar_relatorio_txt() != null){
if(p.getEnviar_relatorio_txt() > 0){
viewHolder.ibPlano.setImageResource(R.drawable.enviar);
viewHolder.ibPlano.setEnabled(true);
}else{
viewHolder.ibPlano.setImageResource(R.drawable.enviar_2);
viewHolder.ibPlano.setEnabled(false);
}
viewHolder.tvPlano.setText("Enviar");
}else if(p.getMeusDados() != null){
if(p.getMeusDados() > 0){
viewHolder.ibPlano.setImageResource(R.drawable.meus_dados);
viewHolder.ibPlano.setEnabled(true);
}else{
viewHolder.ibPlano.setImageResource(R.drawable.meus_dados_2);
viewHolder.ibPlano.setEnabled(false);
}
viewHolder.tvPlano.setText("Meus Dados");
}else if(p.getRecebimentos_pendentes() != null){
if(p.getRecebimentos_pendentes() > 0){
viewHolder.ibPlano.setImageResource(R.drawable.recebimentos_pendentes);
viewHolder.ibPlano.setEnabled(true);
}else{
viewHolder.ibPlano.setImageResource(R.drawable.recebimentos_pendentes_2);
viewHolder.ibPlano.setEnabled(true);
}
viewHolder.tvPlano.setText("Recebimentos Pendentes");
}else if(p.getEntregas_pendentes() != null){
if(p.getEntregas_pendentes() > 0){
viewHolder.ibPlano.setImageResource(R.drawable.entregas_pendentes);
viewHolder.ibPlano.setEnabled(true);
}else{
viewHolder.ibPlano.setImageResource(R.drawable.entregas_pendentes_2);
viewHolder.ibPlano.setEnabled(true);
}
viewHolder.tvPlano.setText("Entregas Pendentes");
}else if(p.getAlterar_estoque() != null){
if(p.getAlterar_estoque() > 0){
viewHolder.ibPlano.setImageResource(R.drawable.alterar_estoque);
viewHolder.ibPlano.setEnabled(true);
}else{
viewHolder.ibPlano.setImageResource(R.drawable.alterar_estoque_2);
viewHolder.ibPlano.setEnabled(true);
}
viewHolder.tvPlano.setText("Alterar Estoque");
}
}//final plano lite
return convertView;
}
/** pattern view holder */
private static class ViewHolder{
LinearLayout llPrincipal;
ImageButton ibPlano;
TextView tvPlano;
}
}
set onClick for your ImageButton in getView() method like this:
viewHolder.ibPlano.setOnClickListener(new OnClickListener(){
public void onClick(View v){
// you can get position of clicked item here(you have it in getView argument)
}
});

Unable to refresh the ListView

After i click "more" button, it suppose will extend the listview from 10 to 20.
However after clicked, the list view did not extend and remain original size.
It only can keep the position of scroll bar. This is half of what i need.
newsid = new int[webservice.news.size()];
title = new String[webservice.news.size()];
date = new String[webservice.news.size()];
imagepath = new String[webservice.news.size()];
for (int i = 0; i < webservice.news.size(); i++) {
newsid[i] = webservice.news.get(i).getID();
title[i] = webservice.news.get(i).getNtitle();
date[i] = webservice.news.get(i).getNArticalD();
imagepath[i] = webservice.news.get(i).getImagePath();
}
adapter = new CustomAdapter_ParticularCategoryAllNews(this, title,
date, imagepath);
lv.addFooterView(footermore);
if (constant.isOnline()) {
lv.addFooterView(constant.AdMob());
}
TextView titletext = (TextView) findViewById(R.id.text_pagetitle);
titletext.setText(pagetitletext.toString());
lv.setAdapter(adapter);
This is call when launch activity.
btnmore.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
for (int i = 0; i < webservice.news.size(); i++) {
newsid[i] = webservice.news.get(i).getID();
title[i] = webservice.news.get(i).getNtitle();
date[i] = webservice.news.get(i).getNArticalD();
imagepath[i] = webservice.news.get(i).getImagePath();
}
adapter.setTitle(title);
adapter.setDate(date);
adapter.setImagepath(imagepath);
position = lv.getFirstVisiblePosition();
lv.smoothScrollToPosition(position);
adapter.notifyDataSetChanged();
This is what i call after i click "more button". However the list did not extend from 10 to 20 items.
public class CustomAdapter_ParticularCategoryAllNews extends BaseAdapter {
private Activity activity;
private String[] title, date, imagepath;
private static LayoutInflater inflater = null;
private ImageLoader_Loader imageLoader;
private WindowManager wm = null;
private Display display;
private Config_ConstantVariable constant;
public CustomAdapter_ParticularCategoryAllNews(Activity a, String[] title,
String[] date, String[] imagepath) {
activity = a;
this.title = title;
this.date = date;
this.imagepath = imagepath;
inflater = (LayoutInflater) activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
wm = (WindowManager) activity.getSystemService(Context.WINDOW_SERVICE);
imageLoader = new ImageLoader_Loader(activity.getApplicationContext());
constant = new Config_ConstantVariable(activity);
}
public int getCount() {
return title.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public void setTitle(String[] title) {
this.title = title;
}
public void setDate(String[] date) {
this.date = date;
}
public void setImagepath(String[] imagepath) {
this.imagepath = imagepath;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.main_particularcategoryallnewslist,
parent, false);
LinearLayout linear = (LinearLayout) vi.findViewById(R.id.layout_image);
ImageView imageview = (ImageView) vi
.findViewById(R.id.image_categoryallnewstitle);
TextView titletext = (TextView) vi
.findViewById(R.id.text_categoryallnewstitle);
TextView datetext = (TextView) vi.findViewById(R.id.text_newsdate);
if (!imagepath[position].toString().equals("no picture")) {
imageview.setVisibility(View.VISIBLE);
linear.setVisibility(View.VISIBLE);
imageLoader.DisplayImage(imagepath[position], imageview);
} else {
imageview.setVisibility(View.GONE);
imageview.setImageDrawable(null);
linear.setVisibility(View.GONE);
display = wm.getDefaultDisplay();
int screenWidth = display.getWidth();
titletext.setWidth(screenWidth);
}
if (constant.getscreenresolution() >= 800 && constant.ScreenOrientation() == 1) {
titletext.setTextSize(TypedValue.COMPLEX_UNIT_PX, 30);
datetext.setTextSize(TypedValue.COMPLEX_UNIT_PX, 20);
}
titletext.setText(title[position].toString());
datetext.setText(date[position].toString());
return vi;
}
}
This is the CustomAdapter class.
In your adapter add:
public void setTitle(String[] title) {
this.title = title;
}
public void setDate(String[] date) {
this.date = date;
}
public void setImagepath(String[] imagepath) {
this.imagepath = imagepath;
}
When the more button is pressed call the three methods above with arrays containing 20 objects. Then call notifyDataSetChanged on your adapter.
Update:
This is working for me:
Activity:
public class HelpProjectActivity extends Activity {
private ArrayList<Item> items;
private boolean extend = false;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
createArray();
ListView lv = (ListView)findViewById(R.id.list);
lv.setAdapter(new HelpListAdapter());
}
private void createArray() {
items = new ArrayList<Item>();
for(int i = 0; i < 20; i++) {
Item item = new Item();
item.title = "Title " + i;
item.subtitle = "Subtitle " + i;
item.image = "default";
items.add(item);
}
}
public void morePressed(View v) {
extend = !extend;
Button b = (Button) findViewById(R.id.button);
b.setText(extend ? R.string.less_button : R.string.more_button);
ListView lv = (ListView)findViewById(R.id.list);
((BaseAdapter)lv.getAdapter()).notifyDataSetChanged();
}
private class HelpListAdapter extends BaseAdapter {
#Override
public int getCount() {
if (extend) {
return items.size();
}
return items.size()/2;
}
#Override
public Object getItem(int pos) {
return items.get(pos);
}
#Override
public long getItemId(int pos) {
return pos;
}
#Override
public View getView(int pos, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
v = View.inflate(getApplicationContext(), R.layout.litst_item, null);
}
Item item = items.get(pos);
TextView titleText = (TextView) v.findViewById(R.id.list_item_title);
titleText.setText(item.title);
TextView subtitleText = (TextView) v.findViewById(R.id.list_item_subtitle);
subtitleText.setText(item.subtitle);
ImageView image = (ImageView) v.findViewById(R.id.list_image);
if (item.image.equalsIgnoreCase("default")) {
image.setImageResource(R.drawable.default_list_image);
} else {
// what ever
}
return v;
}
}
}
main.xml:
<?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="fill_parent"
android:orientation="vertical" >
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_margin="10dp"
android:onClick="morePressed"
android:text="#string/more_button" />
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
list_item.xml:
<?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"
android:orientation="horizontal" >
<ImageView
android:id="#+id/list_image"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_margin="5dp"
android:layout_gravity="center_vertical"
android:contentDescription="#string/list_image" />
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical" >
<TextView
android:id="#+id/list_item_title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textStyle="bold" />
<TextView
android:id="#+id/list_item_subtitle"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textStyle="italic" />
</LinearLayout>
</LinearLayout>
Item.java:
public class Item {
String image;
String title;
String subtitle;
}
adapter.notifyDataSetChanged(); try this

Categories

Resources