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);
}
}
Related
I used GridView to display images of types of batteries. When user clicks any image, the features of that particular battery will get print on next page. The images and features are fetching from the server. The problem is the first battery image is displaying when I opened the GridView, but the other battery images are displaying in that GridView only after I scroll the screen two to three times. But I want to display all the images once I opened the GridView.
private void getDatasFromIntent() {
alHM = new ArrayList<>();
Intent intent = getIntent();
String typeResp = intent.getStringExtra("IMG_S");
try {
JSONObject jsonObject = new JSONObject(typeResp);
JSONArray jsonArray = jsonObject.getJSONArray("process");
for (int i = 0; i < jsonArray.length(); i++) {
HashMap<String, String> hm = new HashMap<>();
JSONObject bat_json = jsonArray.getJSONObject(i);
String battery_featues_id = bat_json.getString("battery_featues_id");
String battery = bat_json.getString("battery_type");
String battery_image = bat_json.getString("battery_image");
battery_image = battery_image.replace("\\", "");
hm.put("battery_featues_id", battery_featues_id);
hm.put("battery_type", battery);
hm.put("battery_image", battery_image);
alHM.add(hm);
}
// prepared arraylist and passed it to the Adapter class
mAdapter = new GridviewAdapter(this, alHM);
// Set custom adapter to gridview
GridView gridView = (GridView) findViewById(R.id.gridView1);
gridView.setAdapter(mAdapter);
// Implement On Item click listener
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
Toast.makeText(SampleBatteryList.this, "a: " + mAdapter.getItem(position), Toast.LENGTH_SHORT).show();
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
public class GridviewAdapter extends BaseAdapter {
private ArrayList<HashMap<String, String>> list;
private final SampleBatteryList activity;
public GridviewAdapter(SampleBatteryList sampleBatteryList,
ArrayList<HashMap<String, String>> alHM) {
this.activity = sampleBatteryList;
this.list = alHM;
Log.d("VOLLY", "ADP :" + alHM);
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int i) {
return list.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
public class ViewHolder {
public ImageView imgViewFlag;
public TextView txtViewTitle;
public Button button;
ViewHolder view;
}
#Override
public View getView(int i, View contentView, ViewGroup viewGroup) {
Log.d("VOLLY", "INT : " + i);
ViewHolder view;
LayoutInflater inflator = activity.getLayoutInflater();
if (contentView == null) {
view = new ViewHolder();
contentView = inflator.inflate(R.layout.grid_content_sub, null);
view.txtViewTitle = (TextView)
contentView.findViewById(R.id.tv_battery_type);
view.imgViewFlag = (ImageView)
contentView.findViewById(R.id.img_battery);
view.button = (Button)
contentView.findViewById(R.id.btn_card_type);
contentView.setTag(view);
} else {
view = (ViewHolder) contentView.getTag();
view.txtViewTitle.setText(list.get(i).get("battery_type"));
view.imgViewFlag.setImageResource(R.drawable.branded_logo);
view.imgViewFlag.setImageDrawable(null);
Picasso.with(SampleBatteryList.this)
.load(Links._img + list.get(i).get("battery_image"))
.fit().centerCrop()
.into(view.imgViewFlag);
final int ii = i;
final Button btn = view.button;
view.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
btn.setText(list.get(ii).get("battery_type"));
btn.setSingleLine(true);
YoYo.with(Techniques.TakingOff).duration(2000).playOn(btn);
showDialog();
Log.d("VOLLY", "id :" +list.get(ii).get("battery_featues_id"));
callVollyForFeature(list.get(ii).get("battery_featues_id"));
}
});
}
return contentView;
}
}
here you are using view holder class but after initialization part and assign value part are in if and else so value not showing.
#Override
public View getView(int i, View contentView, ViewGroup viewGroup) {
Log.d("VOLLY", "INT : " + i);
ViewHolder view;
LayoutInflater inflator = activity.getLayoutInflater();
if (contentView == null) {
view = new ViewHolder();
contentView = inflator.inflate(R.layout.grid_content_sub, null);
view.txtViewTitle = (TextView)
contentView.findViewById(R.id.tv_battery_type);
view.imgViewFlag = (ImageView)
contentView.findViewById(R.id.img_battery);
view.button = (Button)
contentView.findViewById(R.id.btn_card_type);
contentView.setTag(view);
} else {
view = (ViewHolder) contentView.getTag();
view.txtViewTitle.setText(list.get(i).get("battery_type"));
view.imgViewFlag.setImageResource(R.drawable.branded_logo);
view.imgViewFlag.setImageDrawable(null);
Picasso.with(SampleBatteryList.this)
.load(Links._img + list.get(i).get("battery_image"))
.fit().centerCrop()
.into(view.imgViewFlag);
final int ii = i;
final Button btn = view.button;
view.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
btn.setText(list.get(ii).get("battery_type"));
btn.setSingleLine(true);
YoYo.with(Techniques.TakingOff).duration(2000).playOn(btn);
showDialog();
Log.d("VOLLY", "id :" +list.get(ii).get("battery_featues_id"));
callVollyForFeature(list.get(ii).get("battery_featues_id"));
}
});
}
return contentView;
}
change to
#Override
public View getView(int i, View contentView, ViewGroup viewGroup) {
Log.d("VOLLY", "INT : " + i);
ViewHolder view;
LayoutInflater inflator = activity.getLayoutInflater();
if (contentView == null) {
view = new ViewHolder();
contentView = inflator.inflate(R.layout.grid_content_sub, null);
view.txtViewTitle = (TextView)
contentView.findViewById(R.id.tv_battery_type);
view.imgViewFlag = (ImageView)
contentView.findViewById(R.id.img_battery);
view.button = (Button)
contentView.findViewById(R.id.btn_card_type);
contentView.setTag(view);
}else{
view = (ViewHolder) contentView.getTag();
}
view.txtViewTitle.setText(list.get(i).get("battery_type"));
view.imgViewFlag.setImageResource(R.drawable.branded_logo);
view.imgViewFlag.setImageDrawable(null);
Picasso.with(SampleBatteryList.this)
.load(Links._img + list.get(i).get("battery_image"))
.fit().centerCrop()
.into(view.imgViewFlag);
final int ii = i;
final Button btn = view.button;
view.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
btn.setText(list.get(ii).get("battery_type"));
btn.setSingleLine(true);
YoYo.with(Techniques.TakingOff).duration(2000).playOn(btn);
showDialog();
Log.d("VOLLY", "id :" +list.get(ii).get("battery_featues_id"));
callVollyForFeature(list.get(ii).get("battery_featues_id"));
}
});
return contentView;
}
I've made a custom adapter for a ListView in order to display a String and an ImageButton within the same row. A row is generated every time the add button is clicked. The string is taken from the EditText field, while the ImageButton bin_button is allocated dinamically. Everything works fine except I can't make the bin_buttons fire an OnClick event.
I've tried several solutions. Here bin_button_listener is generated outside the add_button OnClickListener and then set. I've also tried to set listeners with a new OnClickListener every time a new bin_button was created.
Here some code:
Row layout list_string_button_layout.xml:
<TextView
android:id="#+id/list_item_string"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingStart="8dp"
android:paddingEnd="0dp"
android:paddingTop="8dp"
android:textSize="18sp"
android:textStyle="bold"/>
<ImageButton
android:id="#+id/delete_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="10dp"
android:paddingEnd="5dp"
android:background="#00ffffff"
android:src="#drawable/ic_delete_black_18dp"
android:layout_alignBottom="#+id/list_item_string"
android:layout_alignParentEnd="true"
android:focusableInTouchMode="true"
/>
</RelativeLayout>
Activity layout activity_search.xml:
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/ingredient_text_input"
android:hint="#string/start_typing_ingredient"
android:layout_marginTop="52dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
/>
<Button
style="#style/Button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/add_button"
android:backgroundTint="#color/colorPrimaryLight"
android:id="#+id/add_button"
android:layout_alignTop="#+id/ingredient_text_input"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"/>
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/ingredients_view"
android:layout_above="#+id/search_button"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/add_button" />
</RelativeLayout>
Custom Adapter IngredientBinAdapter:
public class IngredientBinAdapter extends BaseAdapter {
private Context context = null;
private List<HashMap<String,ImageButton>> items = new ArrayList<>();
public IngredientBinAdapter(Context context, ArrayList<HashMap<String,ImageButton>> items){
this.context=context;
this.items=items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int position) {
return items.get(position);
}
#Override
public long getItemId(int position) {
return getItem(position).hashCode();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null)
convertView = LayoutInflater.from(context).inflate(R.layout.list_string_button_layout,null);
HashMap<String,ImageButton> item = (HashMap<String,ImageButton>) getItem(position);
TextView string = (TextView) convertView.findViewById(R.id.list_item_string);
String key=(String) item.keySet().toArray()[0];
string.setText(key);
item.get(key).setImageResource(R.drawable.ic_delete_black_18dp);
return convertView;
}
}
Activity:
public class SearchActivity extends AppCompatActivity{
//getting resources and allocating variables
Button add_button = null;
Button search_button = null;
EditText insert_ingredient = null;
ListView ingredient_list_view = null;
ArrayList<HashMap<String,ImageButton>> ingredient_list = new ArrayList<>();
IngredientBinAdapter list_adapter = new IngredientBinAdapter(this,ingredient_list);
ArrayList<String> ingredients_utils = new ArrayList<>();
View.OnClickListener bin_button_listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
System.out.println("BIN_BUTTON CLICKED");
ImageButton clicked_button = (ImageButton) v;
for(Iterator<HashMap<String,ImageButton>> i = ingredient_list.iterator(); i.hasNext(); ){
HashMap<String,ImageButton> temp= i.next();
if(temp.values().toArray()[0].equals(clicked_button))
ingredient_list.remove(temp);
}
list_adapter.notifyDataSetChanged();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
}
#Override
protected void onStart(){
super.onStart();
add_button = (Button) findViewById(R.id.add_button);
search_button = (Button) findViewById(R.id.search_button2);
insert_ingredient = (EditText) findViewById(R.id.ingredient_text_input);
ingredient_list_view = (ListView) findViewById(R.id.ingredients_view);
ingredient_list_view.setAdapter(list_adapter);
//add_button listener
add_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String current_ingredient_string = insert_ingredient.getText().toString().trim();
if (!current_ingredient_string.isEmpty() && !ingredients_utils.contains(current_ingredient_string)) {
HashMap<String, ImageButton> temp = new HashMap<String, ImageButton>();
ImageButton temp_bin_button = new ImageButton(SearchActivity.this);
temp_bin_button.setOnClickListener(bin_button_listener);
temp.put(current_ingredient_string, temp_bin_button);
ingredient_list.add(temp);
list_adapter.notifyDataSetChanged();
}
ingredients_utils.add(insert_ingredient.getText().toString().trim());
insert_ingredient.getText().clear();
}
});
}
}
first of all
u should move your logic to onCreate() see: Difference between onCreate() and onStart()?
second
u should in your method in adapter :
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// 1. inflate view
// 2. find button
// 3. assign here listener to bin button
// i advice to use convert view pattern
}
some hints :
create data object describing row item
public class BinRow {
private String _someString;
private Drawable _imageDrawable; // (or resource id name)
public String getString() {
return _someString;
}
public Drawable getImage() {
return _imageDrawable;
}
public BinRow(String someText, Drawable imageDrawable) {
_someText = someText;
_imageDrawable = imageDrawable;
}
}
here u have adapter example ( u need adjust Album - to your BinRow & layout for row & convert view items in view holder ) - this should show you idea how adapter works :
public class AlbumAdapter extends BaseAdapter implements IListAdapter<Album> {
private List<Album> _albums;
private Context _context;
private LayoutInflater _layoutInflater;
static class ViewHolder {
ImageView imageView;
TextView albumName;
public ViewHolder(View v) {
imageView = (ImageView) v.findViewById(R.id.image);
albumName = (TextView) v.findViewById(R.id.tvAlbumName);
}
}
public AlbumAdapter(List<Album> albums) {
if(albums == null) {
_albums = new ArrasyList<>();
} else {
_albums = albums;
}
}
#Override
public int getCount() {
return _albums.size();
}
#Override
public Album getItem(int position) {
return _albums.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, final ViewGroup parent) {
final Album album = getItem(position);
if (_context == null) {
_context = parent.getContext();
}
if (_layoutInflater == null) {
_layoutInflater = LayoutInflater.from(_context);
}
View _view = convertView;
ViewHolder viewHolder;
if (_view == null) {
_view = _layoutInflater.inflate(R.layout.album_item_layout, parent, false);
viewHolder = new ViewHolder(_view);
_view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) _view.getTag();
}
viewHolder.albumName.setText(album.getAlbumDescription());
// here u can set: image to image view & listener to image
// image view could be a button
viewHolder.imageView.setOnClickListener(View.OnClickListener);
return _view;
}
#Override
public void add(Album listElement) {
_albums.add(listElement);
}
#Override
public void addAll(List<Album> listOfElements) {
_albums.addAll(listOfElements);
}
#Override
public void clear() {
_albums.clear();
}
#Override
public void remove(Album listElement) {
_albums.remove(listElement);
}
}
public interface IListAdapter<T> {
void add(T listElement);
void addAll(List<T> listOfElements);
void clear();
void remove(T listElement);
}
above interface serves as helper for adapter list methods
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"
public class MainActivity extends Activity {
Button okButton;
EditText wishEditText;
ListView wishListView;
BaseAdapter adapter;
ArrayList<list_item>arrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 0);
setContentView(R.layout.activity_main);
initializedAll();
}
public void initializedAll() {
okButton = (Button) findViewById(R.id.button1);
wishEditText = (EditText) findViewById(R.id.editText1);
wishListView = (ListView) findViewById(R.id.listView1);
arrayList = new ArrayList<list_item>();
adapter = new BaseAdapter() {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
#Override
public View getView(int position, View view, ViewGroup viewGroupgroup) {
if (view==null) {
view = inflater.inflate(R.layout.wish_list_item, null);
}
TextView wishText = (TextView) findViewById(R.id.wishItemtextView);
TextView dateText = (TextView) findViewById(R.id.wishDatetextView);
wishText.setText(arrayList.get(position).getWishString());
Date date = arrayList.get(position).getDate();
dateText.setText(DateFormat.format("dd/MM/yyyy HH:mm:ss a", date));
return view;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return arrayList.get(position);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return arrayList.size();
}
};
wishListView.setAdapter(adapter);
okButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String string = wishEditText.getText().toString();
Date date = new Date();
list_item item = new list_item(date,string);
arrayList.add(item);
adapter.notifyDataSetChanged();
wishEditText.setText("");
InputMethodManager inputMethodManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(wishEditText.getWindowToken(), 0);
Toast.makeText(getBaseContext(), "New wish Added To List", Toast.LENGTH_SHORT);
}
});
};
}
Please help me.
When I pressed OK button then my apps has stop but there is no error even eclipse do't show any error.
How I can solve it?
Please help me.
This like inputMethodManager.hideSoftInputFromWindow(wishEditText.getWindowToken(), 0); might be giving you a NullPointerException
Try this way,hope this will help you to solve your problem.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:padding="5dp">
<EditText
android:id="#+id/edtWishText"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"/>
<Button
android:id="#+id/btnAddWishText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:text="Add"/>
</LinearLayout>
<ListView
android:id="#+id/lstWish"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:divider="#android:color/white"
android:dividerHeight="1dp"/>
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="5dp">
<TextView
android:id="#+id/txtWishText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/txtWishDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp"/>
</LinearLayout>
public class MainActivity extends Activity{
private ListView lstWish;
private EditText edtWishText;
private Button btnAddWishText;
private WishListAdapter listAdapter;
private ArrayList<HashMap<String,Object>> wishList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 0);
setContentView(R.layout.activity_main);
lstWish = (ListView) findViewById(R.id.lstWish);
edtWishText = (EditText) findViewById(R.id.edtWishText);
btnAddWishText = (Button) findViewById(R.id.btnAddWishText);
wishList =new ArrayList<HashMap<String, Object>>();
listAdapter = new WishListAdapter(this,wishList);
lstWish.setAdapter(listAdapter);
btnAddWishText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(edtWishText.getText() == null && edtWishText.getText().toString().length()<=0){
edtWishText.setError("Value required");
}else{
HashMap<String,Object> data = new HashMap<String, Object>();
data.put("WishText",edtWishText.getText().toString());
data.put("WishText",new Date());
wishList.add(data);
listAdapter.notifyDataSetChanged();
edtWishText.setText("");
((InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(edtWishText.getWindowToken(), 0);
Toast.makeText(getBaseContext(), "New wish Added To List", Toast.LENGTH_SHORT).show();
}
}
});
}
class WishListAdapter extends BaseAdapter{
private Context mContext;
public ArrayList<HashMap<String,Object>> wishList;
public WishListAdapter(Context mContext,ArrayList<HashMap<String,Object>> wishList)
{
this.mContext = mContext;
this.wishList = wishList;
}
#Override
public int getCount(){
return wishList.size();
}
#Override
public Object getItem(int position)
{
return wishList.get(position);
}
#Override
public long getItemId(int position)
{
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView==null){
holder = new ViewHolder();
convertView = LayoutInflater.from(mContext).inflate(R.layout.list_item,null,false);
holder.txtWishText = (TextView) convertView.findViewById(R.id.txtWishText);
holder.txtWishDate = (TextView) convertView.findViewById(R.id.txtWishDate);
convertView.setTag(holder);
}else{
holder = (ViewHolder)convertView.getTag();
}
holder.txtWishText.setText(wishList.get(position).get("wishText").toString());
holder.txtWishDate.setText(DateFormat.format("dd/MM/yyyy HH:mm:ss a",(Date)wishList.get(position).get("WishDate")));
return convertView;
}
}
public static class ViewHolder
{
public TextView txtWishText;
public TextView txtWishDate;
}
}
i need to get the check-box state from a grid-view when clicking on a button
i tried many things but the state is always "false"
here is my code
this is the adapter
public class CustomSuggestFriends extends ArrayAdapter<Items_FriendsRequest> {
Context context;
dbManage objDB;
Items_FriendsRequest Items_SuggestFriends;
List<Items_FriendsRequest>items;
int Position;
SharedPreferences SharedP;
String user_id="1002", secret_id = "2143054018";
String u_id="1025", ut_ = "1";
public CustomSuggestFriends(Context context, int textViewResourceId,
List<Items_FriendsRequest> objects) {
super(context, textViewResourceId, objects);
this.context = context;
}
private class viewHolder {
private ImageView userImage;
private TextView userName;
private CheckBox checkbox;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
viewHolder holder = null;
ImageLoader_Crop imageLoader_Crop;
Items_SuggestFriends = getItem(position);
Position = position;
objDB = new dbManage(getContext());
items = objDB.select_SuggestFriends();
objDB.CloseDataBase();
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
imageLoader_Crop = new ImageLoader_Crop(context.getApplicationContext());
if (convertView == null) {
convertView = inflater.inflate(R.layout.items_suggestdriends, null);
holder = new viewHolder();
holder.userImage = (ImageView) convertView
.findViewById(R.id.Items_SuggestFriends_userImage);
holder.userName = (TextView) convertView
.findViewById(R.id.Items_SuggestFriends_NameTXT);
holder.checkbox = (CheckBox) convertView
.findViewById(R.id.Items_SuggestFriends_checkBox);
holder.checkbox.setTag(position);
holder.checkbox.setChecked(items.get(position).isSelected());
holder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int getPosition = (Integer) buttonView.getTag(); // Here we get the position that we have set for the checkbox using setTag.
items.get(getPosition).setSelected(buttonView.isChecked()); // Set the value of checkbox to maintain its state.
Log.v("Changed",items.get(getPosition).getId_()+"");
}
});
convertView.setTag(holder);
} else {
holder = (viewHolder) convertView.getTag();
}
holder.userName.setText(Items_SuggestFriends.getName_());
String SuggestF = Items_SuggestFriends.getSuggestFriendsSEND();
if (SuggestF.equals("0")) {
holder.checkbox.setVisibility(View.VISIBLE);
} else if (SuggestF.equals("1")) {
holder.checkbox.setVisibility(View.GONE);
}
String imageURL = "";
imageURL = functionspackage.Constants.server_file + "1/s/"
+ Items_SuggestFriends.getId_() + "."
+ Items_SuggestFriends.getRand_() + ".jpg";
holder.userImage.setTag(imageURL);
imageLoader_Crop.DisplayImage(imageURL, context, holder.userImage);
return convertView;
}
}
this is my class its got a button called send
and in this button i need to get the ids of what is cheked
public class SuggestFriends extends Activity {
int count;
dbManage objDB;
SharedPreferences SharedP;
String user_id, secret_id = "";
public static String u_id, ut_ = "";
Button send, cancel;
List<Items_FriendsRequest> SuggestFriendsItems;
GridView gridView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.displayphoto_from_album);
initialise_View();
here i need to get the values but its always false!!!!
send.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
count = gridView.getCount();
objDB = new dbManage(SuggestFriends.this);
SuggestFriendsItems = objDB.select_SuggestFriends();
objDB.CloseDataBase();
SparseBooleanArray sparseBooleanArray = gridView
.getCheckedItemPositions();
// add the id of the ones that been checked . . to string with
// (,)
for (int i = 0; i < count; i++) {
if(sparseBooleanArray.valueAt(i) == true) {
Log.e(sparseBooleanArray.get(i)+"",SuggestFriendsItems.get(i).getId_()+"");
} else if (!sparseBooleanArray.get(i)) {
Log.e(sparseBooleanArray.get(i) +"",SuggestFriendsItems.get(i).getId_()+"");
gridView.getItemAtPosition(i);
}
}
}
});
SharedP = getSharedPreferences(functionspackage.Constants.SharedP_name,
0);
user_id = SharedP.getString(functionspackage.Constants.SharedP_user_id,
null);
secret_id = SharedP.getString(
functionspackage.Constants.SharedP_secret_id, null);
if (getIntent().hasExtra(functionspackage.Constants.Extra_Uid)) {
u_id = getIntent().getStringExtra(
functionspackage.Constants.Extra_Uid);
}
if (getIntent().hasExtra(functionspackage.Constants.Extra_ut)) {
ut_ = getIntent().getStringExtra(
functionspackage.Constants.Extra_ut);
}
SuggestFriends_AsyncTask Async = new SuggestFriends_AsyncTask();
Async.execute(user_id, secret_id, u_id, ut_);
}
// ///////////////////////////////////////////////////////////////
// ///////////////////////////////////////////////////////////////
// ///////////////////////////////////////////////////////////////
String response = "";
class SuggestFriends_AsyncTask extends AsyncTask<String, Integer, String> {
#Override
protected String doInBackground(String... params) {
response = "";
response = functionspackage.methodes.HTTP_fileInf_OPhotos(
functionspackage.Constants.server_Web_Profiles
+ "/suggest/" + params[3] + "/" + params[2],
params[0], params[1], 0);
functionspackage.methodes.install_JSON_SuggestFriends(
SuggestFriends.this, response);
objDB = new dbManage(SuggestFriends.this);
SuggestFriendsItems = objDB.select_SuggestFriends();
objDB.CloseDataBase();
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
CustomSuggestFriends adapterSuggestFriends = new CustomSuggestFriends(
SuggestFriends.this, R.layout.items_suggestdriends,
SuggestFriendsItems);
gridView.setAdapter(adapterSuggestFriends);
gridView.setChoiceMode(GridView.CHOICE_MODE_MULTIPLE);
}
}
// ///////////////////////////////////////////////////////////////
// ///////////////////////////////////////////////////////////////
// ///////////////////////////////////////////////////////////////
private void initialise_View() {
gridView = (GridView) findViewById(R.id.DisplayPhoto_gridView);
gridView.setNumColumns(3);
gridView.setBackgroundColor(Color.BLACK);
send = (Button) findViewById(R.id.SendSuggestBotton);
cancel = (Button) findViewById(R.id.CancelsuggestFrindes);
}
}
this is the log
Use a Sparse Boolean Array
Check this link here
https://groups.google.com/forum/?fromgroups#!topic/android-developers/No0LrgJ6q2M
Check Romain Guy Solution. Use GridView instead of Listview.
Similar to the one answered here. Instead of listview use gridview.
in gridview checkbox is unchecked while scrolling gridview up and down
Heres' another example. Same use gridview instead of Listview
How to change the text of a CheckBox in listview?
Here's the complete example
public class MainActivity extends Activity implements
AdapterView.OnItemClickListener {
int count;
private CheckBoxAdapter mCheckBoxAdapter;
String[] GENRES = new String[] {
"Action", "Adventure", "Animation", "Children", "Comedy",
"Documentary", "Drama",
"Foreign", "History", "Independent", "Romance", "Sci-Fi",
"Television", "Thriller"
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final GridView listView = (GridView) findViewById(R.id.lv);
// listView.setItemsCanFocus(false);
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(this);
mCheckBoxAdapter = new CheckBoxAdapter(this, GENRES);
listView.setAdapter(mCheckBoxAdapter);
Button b= (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
StringBuilder result = new StringBuilder();
result.append("Checked at position");
result.append("\n");
for(int i=0;i<mCheckBoxAdapter.mCheckStates.size();i++)
{
if(mCheckBoxAdapter.mCheckStates.get(i)==true)
{
result.append(mCheckBoxAdapter.mCheckStates.get(i)+" at"+i);
result.append("\n");
}
}
Toast.makeText(MainActivity.this, result, 10000).show();
}
});
}
public void onItemClick(AdapterView parent, View view, int
position, long id) {
mCheckBoxAdapter.toggle(position);
}
class CheckBoxAdapter extends ArrayAdapter implements CompoundButton.OnCheckedChangeListener
{ private SparseBooleanArray mCheckStates;
LayoutInflater mInflater;
TextView tv1,tv;
CheckBox cb;
String[] gen;
CheckBoxAdapter(MainActivity context, String[] genres)
{
super(context,0,genres);
mCheckStates = new SparseBooleanArray(genres.length);
mInflater = (LayoutInflater)MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
gen= genres;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return gen.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 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View vi=convertView;
if(convertView==null)
vi = mInflater.inflate(R.layout.checkbox, null);
tv= (TextView) vi.findViewById(R.id.textView1);
cb = (CheckBox) vi.findViewById(R.id.checkBox1);
tv.setText("Name :"+ gen [position]);
cb.setTag(position);
cb.setChecked(mCheckStates.get(position, false));
cb.setOnCheckedChangeListener(this);
return vi;
}
public boolean isChecked(int position) {
return mCheckStates.get(position, false);
}
public void setChecked(int position, boolean isChecked) {
mCheckStates.put(position, isChecked);
}
public void toggle(int position) {
setChecked(position, !isChecked(position));
}
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
}
}
activit_main.xml
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<GridView
android:id="#+id/lv"
android:layout_width="wrap_content"
android:numColumns="2"
android:layout_height="wrap_content"
android:layout_above="#+id/button1"/>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="Button" />
</RelativeLayout>
checkbox.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="15dp"
android:layout_marginTop="34dp"
android:text="TextView" />
<CheckBox
android:id="#+id/checkBox1"
android:focusable="false"
android:focusableInTouchMode="false"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="#+id/textView1"
android:layout_marginRight="22dp"
android:layout_marginTop="23dp" />
</RelativeLayout>
Snap shot
There is a lot of unecessary code in you question in my opinion (way better than too little, though), try change:
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int getPosition = (Integer) buttonView.getTag(); // Here we get the position that we have set for the checkbox using setTag.
// -- buttonView.isChecked() changed to isChecked -- //
items.get(getPosition).setSelected(isChecked); // Set the value of checkbox to maintain its state.
Log.v("Changed",items.get(getPosition).getId_()+"");
}
If that does not work please show clearly where you read the false value and expect true.