How should I pass an Arraylist to BaseAdapter in android? - android

I have the following problem. I am not able pass the Arraylist to another Activity which extends BaseActivity.
ListViewAdapter.java
package com.example.coherendz.uobgoldandsilver;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.ArrayList;
public class ListViewAdapter extends BaseAdapter {
ArrayList<String> myList = new ArrayList();
ArrayList<String> selectedList = new ArrayList();
LayoutInflater inflater,layout;
Context context;
private ArrayList currency,weight,Buy,Sell;
ArrayList<String> names= new ArrayList<String>();
Activity a;
public ListViewAdapter(ArrayList myList,ArrayList names,ArrayList currency,ArrayList weight,ArrayList Buy,ArrayList Sell, Context context) {
this.myList = myList;
this.names = names;
this.currency = currency;
this.weight = weight;
this.Buy = Buy;
this.Sell = Sell;
this.context = context;
inflater = LayoutInflater.from(this.context);
}
public ListViewAdapter(Context context,ArrayList<String> selectedList){
layout = LayoutInflater.from(context);
this.selectedList = selectedList;
}
#Override
public int getCount() {
return myList.size();
}
#Override
public Object getItem(int position) {
return myList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
MyViewHolder mViewHolder=null;
if(convertView == null) {
convertView = inflater.inflate(R.layout.custom_row, null);
mViewHolder = new MyViewHolder(convertView);
convertView.setTag(mViewHolder);
} else {
mViewHolder = (MyViewHolder) convertView.getTag();
}
String name="",weig="",buy="",sell="";
String temp_name="";
if(selectedList.size()== 7 || selectedList.isEmpty())
{
/*for(int i =0;i<=names.size();i++)
{
for (int j = 1; j < names.size(); j++)
{
//name = names.get(i).toString();
name = names.get(position).toString();
temp_name = names.get(j).toString();
mViewHolder.tvTitle.setText(name);
if (temp_name.isEmpty()) {
temp_name = name;
mViewHolder.tvTitle.setText(temp_name);
} else {
mViewHolder.tvTitle.setText(name);
}
}
names.clear();
}*/
/*for(String s : names)
{
name = names.get(position).toString();
if(name.isEmpty())
{
mViewHolder.tvTitle.setText(temp_name);
}
else
{
mViewHolder.tvTitle.setText(name);
}
temp_name = name;
}*/
name = names.get(position).toString();
weig = weight.get(position).toString();
buy = Buy.get(position).toString();
sell = Sell.get(position).toString();
mViewHolder.tvTitle.setText(name);
mViewHolder.tvQty.setText(weig);
mViewHolder.tvBuy.setText(buy);
mViewHolder.tvSell.setText(sell);
}
else
{
StringBuilder string1 = new StringBuilder();
for(int i=0; i<selectedList.size();i++){
string1.append(selectedList.get(i).toString());
}
Log.i("Srikanth.M",string1.toString());
for(int j = 0;j<names.size();j++)
{
if(selectedList.contains(names.get(j)))
{
name = names.get(position).toString();
weig = weight.get(position).toString();
buy = Buy.get(position).toString();
sell = Sell.get(position).toString();
mViewHolder.tvTitle.setText(name);
mViewHolder.tvQty.setText(weig);
mViewHolder.tvBuy.setText(buy);
mViewHolder.tvSell.setText(sell);
}
}
}
return convertView;
}
private class MyViewHolder {
TextView tvTitle,tvQty,tvBuy,tvSell;
MyViewHolder(View v){
tvTitle = (TextView) v.findViewById(R.id.tvName);
tvQty = (TextView) v.findViewById(R.id.tvQty);
tvBuy = (TextView) v.findViewById(R.id.tvBuy);
tvSell = (TextView) v.findViewById(R.id.tvSell);
}
}
}
Settings.java
package com.example.coherendz.uobgoldandsilver;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.CheckBox;
import java.util.ArrayList;
public class Settings extends ActionBarActivity {
private String arbo,cas;
ArrayList<String> selectedList = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.actvity_settings);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_settings, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_click) {
ListViewAdapter adapter = new ListViewAdapter(this,selectedList);
finish();
}
return super.onOptionsItemSelected(item);
}
public void onCheckboxClicked(View view) {
// Is the view now checked?
boolean checked = ((CheckBox) view).isChecked();
// Check which checkbox was clicked
switch (view.getId()) {
case R.id.cbArgor:
if (checked) {
CheckBox arbor = (CheckBox) findViewById(R.id.cbArgor);
arbo = arbor.getText().toString();
Log.i("Srikanth", arbo);
selectedList.add(arbo);
}
// Put some meat on the sandwich
else {
selectedList.remove(0);
Log.i("Srikanth","Removed Argo");
}
// Remove the meat
break;
case R.id.cbCast:
if (checked) {
CheckBox cast = (CheckBox) findViewById(R.id.cbCast);
cas = cast.getText().toString();
Log.i("Srikanth", cas);
selectedList.add(cas);
}
// Cheese me
else {
selectedList.remove(cas);
Log.i("Srikanth","Removed Cast");
}
// I'm lactose intolerant
break;
case R.id.cbGoldCertificate:
if (checked) {
}
// Cheese me
else {
}
// I'm lactose intolerant
break;
case R.id.cbGoldSavings:
if (checked) {
}
// Cheese me
else {
}
// I'm lactose intolerant
break;
case R.id.cbGoldBullion:
if (checked) {
}
// Cheese me
else {
}
// I'm lactose intolerant
break;
case R.id.cbPampGoldBars:
if (checked) {
}
// Cheese me
else {
}
// I'm lactose intolerant
break;
case R.id.cbPampGoldBarsWithHook:
if (checked) {
}
// Cheese me
else {
}
// I'm lactose intolerant
break;
case R.id.cbSilverPassbookAccount:
if (checked) {
}
// Cheese me
else {
}
// I'm lactose intolerant
break;
}
StringBuilder string = new StringBuilder();
for(int i=0; i<selectedList.size();i++){
string.append(selectedList.get(i).toString());
}
Log.i("Srikanth.S",string.toString());
}
}
I am not able to retrieve the values of selectedList.
Any Suggestions ?

Because you are adding values to selectedList and not to your adapter data.
Step1: Add those methods in your adapter:
public void addItem(String item){
this.selectedList.add(item);
notifyDataSetChanged();
}
public void removeItem(int position){
this.selectedList.remove(position);
notifyDataSetChanged();
}
Step2: In your Settings Acitvity:
1) Make ListViewAdapter adapter as class variable.
2) Replace all those calls:
selectedList.add(...); by adapter.addItem(...);
and selectedList.remove(...); by adapter.removeItem(...);

Related

Android: radio group in list view not working

When i click the radio group from the first item all the
corresponding items should be selected when the check box is checked
if the check box is not checked then the corresponding items radio
button should not be checked.
if i click in between then first item radio button should be
deselect else if i click the unchecked radio button the check box
should be checked and radio button also be checked. This is what i
want to achieve in this.
My problem from the below code is when i click the first item all the items getting selected but if i click another item in between the first item is getting deselected and the button which i clicked is re positioned
TeacherAssessmentFragmentChild.java
package com.example.playit;
import java.util.ArrayList;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
#SuppressLint("NewApi")
public class TeacherAssessmentFragmentChild extends Fragment {
static Context context;
ArrayList<TeacherAssessmentFragmentChildContainer> assessmentContainer=new ArrayList<>();
View rootView ;
ListView lstassessment;
TeacherAssessmentFragmentChildListAdapter listAdapter;
#Override
public View onCreateView(final LayoutInflater inflater, final ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.teacher_asseessment_view_fragment_child,
container, false);
Initialize();
context = TeacherAssessmentFragment.context;
assessmentContainer.add(new TeacherAssessmentFragmentChildContainer("Chapter", "-1"));
assessmentContainer.add(new TeacherAssessmentFragmentChildContainer("Chp - 1 Algebra", "1"));
assessmentContainer.add(new TeacherAssessmentFragmentChildContainer("Chp - 2 Trignomentry", "-1"));
assessmentContainer.add(new TeacherAssessmentFragmentChildContainer("Chp - 3 Integration", "4"));
assessmentContainer.add(new TeacherAssessmentFragmentChildContainer("Chp - 4 Differentiation", "3"));
assessmentContainer.add(new TeacherAssessmentFragmentChildContainer("Chp - 5 Abacus", "2"));
assessmentContainer.add(new TeacherAssessmentFragmentChildContainer("Chp - 6 Numbersystem", "-1"));
assessmentContainer.add(new TeacherAssessmentFragmentChildContainer("Chp - 7 Algebra", "-1"));
assessmentContainer.add(new TeacherAssessmentFragmentChildContainer("Chp - 8 Algebra", "2"));
listAdapter=new TeacherAssessmentFragmentChildListAdapter(context, 0, assessmentContainer);
lstassessment.setAdapter(listAdapter);
listAdapter.notifyDataSetChanged();
return rootView;
}
public void Initialize() {
lstassessment=(ListView) rootView.findViewById(R.id.teacher_assessment_view_fragment_clild_assessment_list);
}
}
TeacherAssessmentFragmentChildContainer.java
package com.example.playit;
public class TeacherAssessmentFragmentChildContainer {
String chapterName,moduleSelected;
Boolean ismoduleActive;
public TeacherAssessmentFragmentChildContainer(String chapterName,
String moduleSelected) {
super();
this.chapterName = chapterName;
this.moduleSelected = moduleSelected;
if(moduleSelected.equalsIgnoreCase("-1"))
ismoduleActive=false;
else
ismoduleActive=true;
}
public Boolean getIsmoduleActive() {
return ismoduleActive;
}
public void setIsmoduleActive(Boolean ismoduleActive) {
this.ismoduleActive = ismoduleActive;
}
public String getChapterName() {
return chapterName;
}
public String getModuleSelected() {
return moduleSelected;
}
public void setModuleSelected(String moduleSelected) {
this.moduleSelected = moduleSelected;
}
}
TeacherAssessmentFragmentChildListAdapter
package com.example.playit;
import java.util.ArrayList;
import android.annotation.SuppressLint;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
#SuppressLint("NewApi")
public class TeacherAssessmentFragmentChildListAdapter extends
ArrayAdapter<TeacherAssessmentFragmentChildContainer> {
static Context context;
static ArrayList<TeacherAssessmentFragmentChildContainer> container = new ArrayList<>();
ViewHolder holder;
static int checkBoxCount = 0, radioCount = 0, selectedPosition = -1;
public TeacherAssessmentFragmentChildListAdapter(Context context,
int resource,
ArrayList<TeacherAssessmentFragmentChildContainer> container) {
super(context, resource, container);
this.context = context;
this.container = container;
}
#Override
public int getViewTypeCount() {
// Count=Size of ArrayList.
return container.size();
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return super.getCount();
}
public class ViewHolder {
TextView txvchapterName;
CheckBox ckbselectName;
RadioGroup rgassessment;
RadioButton assessment1, assessment2, assessment3, assessment4,
assessment5;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// System.out.println("getview:" + position + " " + convertView);
View row = convertView;
if (row == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater
.inflate(
R.layout.teacher_assessment_view_fragment_child_list_adapter,
parent, false);
holder = new ViewHolder();
holder.txvchapterName = (TextView) row
.findViewById(R.id.teacher_view_fragment_child_list_adapter_chapter);
holder.ckbselectName = (CheckBox) row
.findViewById(R.id.teacher_view_fragment_child_list_adapter_select);
holder.rgassessment = (RadioGroup) row
.findViewById(R.id.teacher_view_fragment_child_list_adapter_assessment_group);
holder.assessment1 = (RadioButton) holder.rgassessment
.findViewById(R.id.teacher_view_fragment_child_list_adapter_assessment1);
holder.assessment2 = (RadioButton) holder.rgassessment
.findViewById(R.id.teacher_view_fragment_child_list_adapter_assessment2);
holder.assessment3 = (RadioButton) holder.rgassessment
.findViewById(R.id.teacher_view_fragment_child_list_adapter_assessment3);
holder.assessment4 = (RadioButton) holder.rgassessment
.findViewById(R.id.teacher_view_fragment_child_list_adapter_assessment4);
holder.assessment5 = (RadioButton) holder.rgassessment
.findViewById(R.id.teacher_view_fragment_child_list_adapter_assessment5);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
if (position == 0) {
holder.assessment1.setButtonDrawable(android.R.drawable.btn_radio);
holder.assessment2.setButtonDrawable(android.R.drawable.btn_radio);
holder.assessment3.setButtonDrawable(android.R.drawable.btn_radio);
holder.assessment4.setButtonDrawable(android.R.drawable.btn_radio);
holder.assessment5.setButtonDrawable(android.R.drawable.btn_radio);
holder.assessment1.setText("");
holder.assessment2.setText("");
holder.assessment3.setText("");
holder.assessment4.setText("");
holder.assessment5.setText("");
} else {
holder.assessment1.setButtonDrawable(android.R.color.transparent);
holder.assessment2.setButtonDrawable(android.R.color.transparent);
holder.assessment3.setButtonDrawable(android.R.color.transparent);
holder.assessment4.setButtonDrawable(android.R.color.transparent);
holder.assessment5.setButtonDrawable(android.R.color.transparent);
holder.assessment1.setText("M1");
holder.assessment2.setText("M2");
holder.assessment3.setText("M3");
holder.assessment4.setText("M4");
holder.assessment5.setText("M5");
}
holder.ckbselectName.setTag(position);
holder.rgassessment.setTag(position);
SetCheckedRbn(container.get(position).getModuleSelected());
SetCheckedChb(container.get(position).ismoduleActive);
holder.ckbselectName.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
selectedPosition = (Integer) v.getTag();
System.out.println("selectedPosition : "+selectedPosition);
System.out.println("container.get(selectedPosition).getIsmoduleActive() : "+container.get(selectedPosition).getIsmoduleActive());
if(selectedPosition==0){
for(int i=0;i<container.size();i++){
if(!container.get(i).getIsmoduleActive()){
container.get(i).setIsmoduleActive(true);
container.get(i).setModuleSelected("0");
}
else {
container.get(i).setIsmoduleActive(false);
container.get(i).setModuleSelected("-1");
}
}
}
else {
if(!container.get(selectedPosition).getIsmoduleActive()){
container.get(selectedPosition).setIsmoduleActive(true);
container.get(selectedPosition).setModuleSelected("0");
}
else {
container.get(selectedPosition).setIsmoduleActive(false);
container.get(selectedPosition).setModuleSelected("-1");
}
}
System.out.println("container.get(selectedPosition).getIsmoduleActive() : "+container.get(selectedPosition).getIsmoduleActive());
notifyDataSetChanged();
}
});
holder.txvchapterName.setText(container.get(position).getChapterName());
holder.rgassessment
.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
selectedPosition = (Integer) group.getTag();
View radioButtonView = group.findViewById(checkedId);
RadioButton checkedRadioButton = (RadioButton)group.findViewById(checkedId);
int idx = group.indexOfChild(radioButtonView);
if (selectedPosition == 0 && checkedRadioButton.isChecked() ) {
for (int i = 0; i < container.size(); i++) {
if (container.get(i).getIsmoduleActive() || i==0 ){
container.get(i).setModuleSelected("" + idx);
}
else if(i!=0){
container.get(i).setModuleSelected("-1");
container.get(i).setIsmoduleActive(false);
}
}
}
else if(selectedPosition !=0){
container.get(selectedPosition).setIsmoduleActive(
true);
container.get(selectedPosition).setModuleSelected(
"" + idx);
}
checkrb();
}
});
return row;
}
public void SetCheckedRbn(String str) {
switch (str) {
case "0":
holder.assessment1.setChecked(true);
break;
case "1":
holder.assessment2.setChecked(true);
break;
case "2":
holder.assessment3.setChecked(true);
break;
case "3":
holder.assessment4.setChecked(true);
break;
case "4":
holder.assessment5.setChecked(true);
break;
default:
holder.assessment1.setChecked(false);
holder.assessment2.setChecked(false);
holder.assessment3.setChecked(false);
holder.assessment4.setChecked(false);
holder.assessment5.setChecked(false);
break;
}
}
public void SetCheckedChb(Boolean isactive) {
if (isactive)
holder.ckbselectName.setChecked(true);
else
holder.ckbselectName.setChecked(false);
}
public void checkrb() {
int rbcount=0,chcount=0;
String str="";
for(int i=0;i<container.size();i++) {
str=container.get(i).getModuleSelected();
if(str!="-1"){
break;
}
}
for(int i=1;i<container.size() && str!="";i++) {
if(str.equals(container.get(i).getModuleSelected()) && container.get(i).getIsmoduleActive()){
rbcount++;
str=container.get(i).getModuleSelected();
}
if(container.get(i).getIsmoduleActive())
chcount++;
}
if(rbcount!=chcount)
container.get(0).setModuleSelected("-1");
else
container.get(0).setModuleSelected(str);
if(rbcount==container.size())
container.get(0).setIsmoduleActive(true);
else
container.get(0).setIsmoduleActive(false);
notifyDataSetChanged();
}
public void checkchb() {
int chcount=0;
for(int i=0;i<container.size();i++) {
if(container.get(i).getIsmoduleActive())
chcount++;
}
if(chcount==(container.size()-1)){
container.get(0).setIsmoduleActive(true);
}
else
container.get(0).setIsmoduleActive(false);
notifyDataSetChanged();
}
}

wrong item is being selected in listview when selecting checkbox

**
When i select the items which are at the bottom of the listview,they wont get selected,
rather only first four items in the list is being selected.its because the items are out of view.
what to do to get these items in view ??sometimes the item gets randomly selected.
Please help me.
thank you
Here is my code**
Main activity
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
public class ExceptionAppActivity extends Activity implements OnClickListener, OnItemSelectedListener {
private final int REQUEST_CODE = 20;
String flagg;
String empNm = Constants.Common.STR_BLNK;
String empCode = Constants.Common.STR_BLNK;
SessionManager session = null;
final Context context = this;
static Typeface custom_font = null;
TextView lblExcId, lblExcEmpNm, lblExcFrmDt, lblExcFrmDtVal, lblExcToDtVal, lblExcTyp, lblExcStat, lblExcEmpCmt;
Button btnExcRej, btnExcApp, btnExcSrch, btnExcExit;
CheckBox cb, chkBox;
ListView excSrchListView;
ArrayList<Excp> Results;
CustomListViewAdapter cla;
ExceptionAppDao eCon = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.exception_app_activity);
/* get Resources from Xml file */
btnExcApp = (Button) findViewById(R.id.btnExcApp);
btnExcRej = (Button) findViewById(R.id.btnExcRej);
btnExcSrch = (Button) findViewById(R.id.btnExcSrch);
btnExcExit = (Button) findViewById(R.id.btnExcExit);
lblExcEmpNm = (TextView) findViewById(R.id.lblExcEmpNm);
lblExcFrmDt = (TextView) findViewById(R.id.lblExcFrmDt);
lblExcFrmDtVal = (TextView) findViewById(R.id.lblExcFrmDtVal);
lblExcToDtVal = (TextView) findViewById(R.id.lblExcToDtVal);
lblExcTyp = (TextView) findViewById(R.id.lblExcTyp);
lblExcStat = (TextView) findViewById(R.id.lblExcStat);
lblExcEmpCmt = (TextView) findViewById(R.id.lblExcEmpCmt);
lblExcId = (TextView) findViewById(R.id.lblExcId);
chkBox = (CheckBox) findViewById(R.id.chkBx);
excSrchListView = (ListView) findViewById(R.id.excSrchListView);
// Session Manager
session = new SessionManager(getApplicationContext());
custom_font = Typeface.createFromAsset(getAssets(), "fonts/DejaVuSans.ttf");
// Connection object for Login
eCon = new ExceptionAppDao(context);
// get User Details from Session
HashMap<String, String> hashMap = new HashMap<String, String>();
hashMap = session.getUserDetails();
empNm = hashMap.get(SessionManager.KEY_EMP_NM);
empCode = hashMap.get(SessionManager.KEY_EMP_CODE);
btnExcApp.setTypeface(custom_font);
btnExcRej.setTypeface(custom_font);
btnExcSrch.setTypeface(custom_font);
btnExcExit.setTypeface(custom_font);
new SyncData(empCode).execute();
if (getIntent().getBooleanExtra("EXIT", false)) {
}
// on click any button
addButtonListener();
}
/**
* on click any button
*/
private void addButtonListener() {
btnExcApp.setOnClickListener(this);
btnExcRej.setOnClickListener(this);
btnExcSrch.setOnClickListener(this);
btnExcExit.setOnClickListener(this);
}
public class SyncData extends AsyncTask<String, String, ArrayList<Excp>> {
private final ProgressDialog dialog = new ProgressDialog(context);
List<ExcpMstVo> rtnExcVo = new ArrayList<ExcpMstVo>();
ExcpMstVo rtnExcMstVo = new ExcpMstVo();
ArrayList<Excp> resultLst = new ArrayList<Excp>();
ExceptionService_Service excpServObj = new ExceptionService_Service();
String syncFlg = Constants.Common.STR_BLNK;
private View rootView;
String flag = "";
int x;
boolean success = false;
boolean successSyncFlag = false;
int countApp = 0;
public SyncData(String str) {
syncFlg = str;
}
public SyncData(View rootView) {
// TODO Auto-generated constructor stub
this.rootView = rootView;
}
#Override
protected ArrayList<Excp> doInBackground(String... params) {
ExceptionSearchCriteria vo = new ExceptionSearchCriteria();
ExcpMstVo excpMstVo = new ExcpMstVo();
try {
if (syncFlg.equals(empCode)) {
vo = setAppData(vo);
rtnExcVo = excpServObj.getExceptionPort().searchExceptionApproval(vo);
if (!(rtnExcVo.isEmpty())) {
System.out.println("rtnExcVo" + rtnExcVo.size());
Excp exc = null;
for (ExcpMstVo excMstVo : rtnExcVo) {
exc = new Excp();
exc.setExcId(excMstVo.getExcpId());
exc.setEmpCode(excMstVo.getEmpCode());
exc.setEmpNm(excMstVo.getEmpnm());
exc.setFromDt(excMstVo.getFromDt());
exc.setToDt(excMstVo.getToDt());
exc.setExcType(excMstVo.getExcpType());
exc.setExcStatus(excMstVo.getStatus());
exc.setEmpComments(excMstVo.getEmpComments());
exc.setExcFor(excMstVo.getExcpFor());
exc.setExcReason(excMstVo.getExcpReason());
resultLst.add(exc);
Results = resultLst;
success = true;
}
}
} else if (btnExcApp.equals(rootView.getRootView().findViewById(rootView.getId()))) {
for (x = excSrchListView.getChildCount() - 1; x >= 0; x--) {
cb = (CheckBox) excSrchListView.getChildAt(x).findViewById(R.id.chkBx);
if (cb.isChecked()) {
excpMstVo = setEmpData();
rtnExcMstVo = excpServObj.getExceptionPort().changeExceptionStatus(excpMstVo);
System.out.println("rtnExcMstVo:::::" + rtnExcMstVo.getExcpId());
System.out.println("rtnExcMstVoStatuss:::::" + rtnExcMstVo.getStatus());
countApp++;
success = false;
}
}
/*if (countApp == 0) {
} else*/ if (countApp > 0) {
new SyncData(rootView).execute();
//flagg = false;
}
System.out.println("rtnExcMstVo:::::" + rtnExcMstVo.getExcpId());
System.out.println("rtnExcMstVoStatuss:::::" + rtnExcMstVo.getStatus());
}
// get dump from device
CopyDbFromDevice cd = new CopyDbFromDevice();
cd.copyDbToSdcard(context);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("success::::" + success);
successSyncFlag = success;
System.out.println("successSyncFlag::::::::" + successSyncFlag);
return resultLst;
}
private ExcpMstVo setEmpData() {
ExcpMstVo excpMstVo = new ExcpMstVo();
excpMstVo.setExcpId(Results.get(x).getExcId());
excpMstVo.setFromDt(Results.get(x).getFromDt());
excpMstVo.setStatus(Constants.Status.STAT_APPRV);
excpMstVo.setMngrComments("");
excpMstVo.setApprovedBy(empCode);
excpMstVo.setLoggedInUser(empCode);
return excpMstVo;
}
private ExceptionSearchCriteria setAppData(ExceptionSearchCriteria vo) {
vo.setApprover(empCode);
vo.setStatus(Constants.Status.PENDING_APPROVAL);
return vo;
}
protected void onPostExecute(ArrayList<Excp> searchResults) {
System.out.println("successSyncFlag1::::::::" + successSyncFlag);
if (successSyncFlag == true) {
System.out.println("entering ON POST IF");
cla = new CustomListViewAdapter(ExceptionAppActivity.this, resultLst);
excSrchListView.setAdapter(cla);
}
else {
System.out.println("ENTERING ONPOST ELSE PART ");
System.out.println("successSyncFlag2:;;;;;; " + successSyncFlag);
System.out.println("success2:::::::::::: " + success);
System.out.println("NEW METHOD STARTED:::::;");
if (countApp == 0) {
System.out.println("ENTERING COUNT APP 0 ");
String flag = "checkItemApp";
dialogBox(flag);
} else {
new SyncData(empCode).execute();
String flag = "excApp";
dialogBox(flag);
System.out.println("NEW METHOD STARTED1:::::::::");
}
}
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
}
}
#Override
public void onClick(View v) {
int countRej = 0;
int id = v.getId();
Intent intent = null;
if (id == R.id.btnExcApp) {
new SyncData(v).execute();
} else if (id == R.id.btnExcRej) {
int itemPos = 0;
for (int y = excSrchListView.getChildCount() - 1; y >= 0; y--) {
cb = (CheckBox) excSrchListView.getChildAt(y).findViewById(R.id.chkBx);
if (cb.isChecked()) {
itemPos = y;
cla.notifyDataSetChanged();
countRej++;
}
}
// Check if any Exception is selected for Rejection and proceed
// accordingly
if (countRej == 1) {
CustomListViewAdapter cla = (CustomListViewAdapter) excSrchListView.getAdapter();
Object o = cla.getItem(itemPos);
Excp selectedExcp = (Excp) o;
intent = new Intent(getBaseContext(), ExcAppDtlsActivity.class);
intent.putExtra("selectedExcp", selectedExcp);
intent.putExtra("readOnly", false);
startActivityForResult(intent, REQUEST_CODE);
} else if (countRej == 0) {
// show dialogue of Select at least 1
String flag = "checkItemRej";
dialogBox(flag);
} else if (countRej > 1) {
String flag = "checkOnlyOne";
dialogBox(flag);
for (int y = excSrchListView.getChildCount() - 1; y >= 0; y--) {
cb = (CheckBox) excSrchListView.getChildAt(y).findViewById(R.id.chkBx);
if (cb.isChecked()) {
itemPos = y;
cb.setChecked(false);
cla.notifyDataSetChanged();
}
}
}
} else if (id == R.id.btnExcSrch) {
intent = new Intent(this, FurtherSearchActivity.class);
intent.putExtra("readOnly", false);
startActivity(intent);
} else if (id == R.id.btnExcExit) {
finish();
}
}
/**
* create alert dialog
*
* #param flag
*/
private void dialogBox(String flag) {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
/*if (flag == "excApp") {
alertDialogBuilder.setTitle("Exception Approved successfully !");
} else*/ if (flag == "checkOnlyOne") {
alertDialogBuilder.setTitle("Please select only one item to reject !");
} else if (flag == "checkItemRej") {
alertDialogBuilder.setTitle("Select Exception to Reject !");
}
/*else if (flag == "checkItemApp") {
alertDialogBuilder.setTitle("Select Exception to Approve !");
} */
else if (flag == "excRej") {
alertDialogBuilder.setTitle("Exception Rejected successfully !");
}
/*else {
alertDialogBuilder.setTitle("Flag - " + flag);
}*/
Dialogbox dbx = new Dialogbox(context);
dbx.createDialogAlert(flag, alertDialogBuilder);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
// TODO Auto-generated method stub
}
#Override
protected void
onActivityResult(int requestCode, int resultCode, Intent data) {
// REQUEST_CODE is defined above
/*
* if (resultCode == RESULT_OK && requestCode == REQUEST_CODE) { //
* Extract name value from result extras flagg =
* data.getExtras().getString("flagg"); if ((flagg.equals("Approve")) ||
* (flagg.equals("Reject"))) { for (int x = 0; x <
* excSrchListView.getChildCount(); x++) { cb = (CheckBox)
* excSrchListView.getChildAt(x).findViewById( R.id.chkBx); if
* (cb.isChecked()) { // If Approval is successful remove from list
* Results.remove(x); cb.setChecked(false); cla.notifyDataSetChanged();
* if (flagg.equals("Approve")) { dialogBox("excApp"); } else {
* dialogBox("excRej"); } } }
*
* } }
*/
}
}
CUSTOM LIST ADAPTER
import java.util.ArrayList;
import java.util.HashMap;
import android.content.Context;
import android.graphics.Typeface;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TableLayout;
import android.widget.TextView;
import com.eanda.smarttime_mobi.R;
import com.eanda.smarttime_mobi.model.Excp;
public class CustomListViewAdapter extends BaseAdapter {
private static ArrayList<Excp> searchArrayList;
HashMap<Integer, Boolean> checked;
private LayoutInflater mInflater;
Typeface custom_font = null;
public CustomListViewAdapter(Context context, ArrayList<Excp> results) {
searchArrayList = results;
mInflater = LayoutInflater.from(context);
checked = new HashMap<Integer, Boolean>(getCount());
custom_font = Typeface.createFromAsset(context.getAssets(), "fonts/DejaVuSans.ttf");
}
public int getCount() {
return searchArrayList.size();
}
public Object getItem(int position) {
return searchArrayList.get(position);
}
public long getItemId(int position) {
return position;
}
// created custom view
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.custom_row_view, null);
holder = new ViewHolder();
holder.myTable = (TableLayout) convertView.findViewById(R.id.myTable);
holder.txtExcId = (TextView) convertView.findViewById(R.id.lblExcId);
holder.txtEmpNm = (TextView) convertView.findViewById(R.id.lblExcEmpNm);
holder.txtFrmDt = (TextView) convertView.findViewById(R.id.lblExcFrmDtVal);
holder.txtToDt = (TextView) convertView.findViewById(R.id.lblExcToDtVal);
holder.txtExcTyp = (TextView) convertView.findViewById(R.id.lblExcTyp);
holder.txtExcStat = (TextView) convertView.findViewById(R.id.lblExcStat);
holder.txtEmpCmt = (TextView) convertView.findViewById(R.id.lblExcEmpCmt);
holder.checkBox = (CheckBox) convertView.findViewById(R.id.chkBx);
convertView.setTag(holder);
convertView.setTag(R.id.chkBx, holder.checkBox);
} else {
holder = (ViewHolder) convertView.getTag();
}
System.out.println("exception_name" + searchArrayList.get(position).getEmpNm());
holder.txtExcId.setText(Integer.toString(searchArrayList.get(position).getExcId()));
holder.txtEmpNm.setText(searchArrayList.get(position).getEmpNm());
holder.txtFrmDt.setText(searchArrayList.get(position).getFromDt());
holder.txtToDt.setText(searchArrayList.get(position).getToDt());
holder.txtExcTyp.setText(searchArrayList.get(position).getExcType());
holder.txtExcStat.setText(searchArrayList.get(position).getExcStatus());
holder.txtEmpCmt.setText(searchArrayList.get(position).getEmpComments());
holder.checkBox.setTag(position);
holder.checkBox.setChecked(searchArrayList.get(position).isChecked());
CheckBox checkBox = (CheckBox) convertView.findViewById(R.id.chkBx);
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
System.out.println("selected");
int checkBoxId = (Integer) buttonView.getTag();
holder.checkBox.setChecked(buttonView.isChecked() ? true : false);
searchArrayList.get(checkBoxId).setChecked(buttonView.isChecked() ? true : false);
System.out.println("checkBoxId " + checkBoxId);
}
});
holder.checkBox.setTag(position);
holder.txtExcId.setTypeface(custom_font);
holder.txtEmpNm.setTypeface(custom_font);
holder.txtFrmDt.setTypeface(custom_font);
holder.txtToDt.setTypeface(custom_font);
holder.txtExcTyp.setTypeface(custom_font);
holder.txtExcStat.setTypeface(custom_font);
holder.txtEmpCmt.setTypeface(custom_font);
return convertView;
}
static class ViewHolder {
TableLayout myTable;
TextView txtExcId;
TextView txtEmpNm;
TextView txtFrmDt;
TextView txtToDt;
TextView txtExcTyp;
TextView txtExcStat;
TextView txtEmpCmt;
CheckBox checkBox;
}
}
CheckBox checkBox = (CheckBox) convertView.findViewById(R.id.chkBx);
You already have check box reference stored in the holder, I wonder why you are initializing it again.
holder.checkBox.setChecked(buttonView.isChecked() ? true : false);
Checked state will be changed when the user clicks the checkbox, so no need to change the checked state again.
Try the following code
----
----
holder.checkBox.setTag(position);
holder.checkBox.setChecked(searchArrayList.get(position).isChecked());
holder.checkBox..setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
System.out.println("selected");
int checkBoxId = (Integer) buttonView.getTag();
searchArrayList.get(checkBoxId).setChecked(buttonView.isChecked() ? true : false);
System.out.println("checkBoxId " + checkBoxId);
}
});
holder.checkBox.setTag(position);
-----
----

RadioButton inside listview

I am using RadioGroup as a row Item inside listview. RadioGroup has 5 radio buttons and I have like 1000 rows. I am not able to mange state of radio buttons.I have tried Map for storing position and checked state. I have even tried making Class and saving checked state and radio button id with setTag() & getTag(). No luck yet. Any suggestions?
Code
Adapter class
package com.example.adapters;
import java.util.List;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.example.android.R;
import com.example.models.AnswerStateModel;
public class AnswerKeyAdapter extends ArrayAdapter<AnswerStateModel> {
private Activity activity;
private List<AnswerStateModel> test;
Toast t = null;
public AnswerKeyAdapter(Activity activity, List<AnswerStateModel> temp) {
super(activity, R.layout.row_item_answer_key, temp);
this.activity = activity;
this.test = temp;
}
#Override
public int getCount() {
return test.size();
}
#Override
public AnswerStateModel getItem(int position) {
return test.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final int currentPosition=position;
View view=null;
if (convertView == null) {
final ViewHolder holder = new ViewHolder();
view = LayoutInflater.from(activity).inflate(
R.layout.row_item_answer_key, parent,false);
holder.lblAnswerId = (TextView) view.findViewById(R.id.lblAnswerId);
holder.rdGroup = (RadioGroup)view.findViewById(R.id.rdGroup);
holder.btnA = (RadioButton) view.findViewById(R.id.btnA);
holder.btnB = (RadioButton) view.findViewById(R.id.btnB);
holder.btnC = (RadioButton) view.findViewById(R.id.btnC);
holder.btnD = (RadioButton) view.findViewById(R.id.btnD);
holder.btnE = (RadioButton) view.findViewById(R.id.btnE);
holder.btnWhat = (Button) view.findViewById(R.id.btnWhat);
view.setTag(holder);
holder.rdGroup.setTag(test.get(position));
holder.rdGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group,
int checkedId) {
AnswerStateModel model=(AnswerStateModel) holder.rdGroup.getTag();
switch (checkedId) {
case R.id.btnA:
model.setChecked(holder.btnA.isChecked());
model.setBtnId(holder.btnA.getId());
break;
case R.id.btnB:
model.setChecked(holder.btnB.isChecked());
model.setBtnId(holder.btnB.getId());
break;
case R.id.btnC:
model.setChecked(holder.btnC.isChecked());
model.setBtnId(holder.btnC.getId());
break;
case R.id.btnD:
model.setChecked(holder.btnD.isChecked());
model.setBtnId(holder.btnD.getId());
break;
case R.id.btnE:
model.setChecked(holder.btnE.isChecked());
model.setBtnId(holder.btnE.getId());
break;
default:
break;
}
}
});
} else{
view=convertView;
((ViewHolder) view.getTag()).rdGroup.setTag(test.get(position));
}
final ViewHolder holder = (ViewHolder) view.getTag();
AnswerStateModel model=(AnswerStateModel)getItem(currentPosition);
holder.btnA.setChecked(false);
holder.btnB.setChecked(false);
holder.btnC.setChecked(false);
holder.btnD.setChecked(false);
holder.btnE.setChecked(false);
switch (model.getBtnId()) {
case R.id.btnA:
holder.btnA.setChecked(test.get(position).isChecked());
break;
case R.id.btnB:
holder.btnB.setChecked(test.get(position).isChecked());
break;
case R.id.btnC:
holder.btnC.setChecked(test.get(position).isChecked());
break;
case R.id.btnD:
holder.btnD.setChecked(test.get(position).isChecked());
break;
case R.id.btnE:
holder.btnE.setChecked(test.get(position).isChecked());
break;
default:
break;
}
holder.lblAnswerId.setText(position+1+"");
holder.btnWhat.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (v.isSelected())
v.setSelected(false);
else
v.setSelected(true);
}
});
return view;
}
private static class ViewHolder {
private TextView lblAnswerId;
private RadioButton btnA;
private RadioButton btnB;
private RadioButton btnC;
private RadioButton btnD;
private RadioButton btnE;
private RadioGroup rdGroup;
private Button btnWhat;
}
void showToast(String text) {
if (t != null)
t.cancel();
t = Toast.makeText(activity, text, Toast.LENGTH_SHORT);
t.show();
}
}
Pojo class
package com.example.models;
public class AnswerStateModel {
private boolean isChecked=false;
private int btnId=0;
private int currentPosition=0;
private String correctAns="";
private int btnPosition=0;
public int getBtnPosition() {
return btnPosition;
}
public void setBtnPosition(int btnPosition) {
this.btnPosition = btnPosition;
}
public String getCorrectAns() {
return correctAns;
}
public void setCorrectAns(String correctAns) {
this.correctAns = correctAns;
}
public boolean isChecked() {
return isChecked;
}
public void setChecked(boolean isChecked) {
this.isChecked = isChecked;
}
public int getBtnId() {
return btnId;
}
public void setBtnId(int btnId) {
this.btnId = btnId;
}
public int getCurrentPosition() {
return currentPosition;
}
public void setCurrentPosition(int currentPosition) {
this.currentPosition = currentPosition;
}
}
Solved it! Used SparseIntArray
Here is the complete code.
/**
*
*/
package com.example.adapters;
import java.util.ArrayList;
import android.app.Activity;
import android.util.SparseIntArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;
import com.example.android.R;
import com.example.models.AnswerStateModel;
import com.example.utils.Config;
public class AnswerKeyAdapter extends ArrayAdapter<AnswerStateModel> {
private Activity activity;
private ArrayList<AnswerStateModel> mAnswerList;
Toast t = null;
private SparseIntArray mSpCheckedState=new SparseIntArray();
public AnswerKeyAdapter(Activity activity, ArrayList<AnswerStateModel> mAnswerList) {
super(activity, R.layout.row_item_answer_key, mAnswerList);
this.activity = activity;
this.mAnswerList = mAnswerList;
}
#Override
public int getCount() {
return mAnswerList.size();
}
#Override
public AnswerStateModel getItem(int position) {
return mAnswerList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder=null;
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(activity).inflate(
R.layout.row_item_answer_key, parent, false);
holder.lblAnswerId = (TextView) convertView.findViewById(R.id.lblAnswerId);
holder.rdGroup = (RadioGroup) convertView.findViewById(R.id.rdGroup);
holder.btnA = (RadioButton) convertView.findViewById(R.id.btnA);
holder.btnB = (RadioButton) convertView.findViewById(R.id.btnB);
holder.btnC = (RadioButton) convertView.findViewById(R.id.btnC);
holder.btnD = (RadioButton) convertView.findViewById(R.id.btnD);
holder.btnE = (RadioButton) convertView.findViewById(R.id.btnE);
holder.btnWhat = (Button) convertView.findViewById(R.id.btnWhat);
convertView.setTag(holder);
} else {
holder=(ViewHolder)convertView.getTag();
}
holder.rdGroup.setOnCheckedChangeListener(null);
holder.rdGroup.clearCheck();
Config.error("Spars "+mSpCheckedState.get(position));
if(mSpCheckedState.indexOfKey(position)>-1){
holder.rdGroup.check(mSpCheckedState.get(position));
}else{
holder.rdGroup.clearCheck();
}
holder.rdGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if(checkedId>-1){
mSpCheckedState.put(position, checkedId);
}else{
if(mSpCheckedState.indexOfKey(position)>-1)
mSpCheckedState.removeAt(mSpCheckedState.indexOfKey(position));
}
}
});
Config.error("Current Position " + position);
holder.lblAnswerId.setText(position + 1 + "");
holder.btnWhat.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (v.isSelected())
v.setSelected(false);
else
v.setSelected(true);
}
});
return convertView;
}
private static class ViewHolder {
private TextView lblAnswerId;
private RadioButton btnA;
private RadioButton btnB;
private RadioButton btnC;
private RadioButton btnD;
private RadioButton btnE;
private RadioGroup rdGroup;
private Button btnWhat;
}
void showToast(String text) {
if (t != null)
t.cancel();
t = Toast.makeText(activity, text, Toast.LENGTH_SHORT);
t.show();
}
}

delete multiple items in custom listview

I want to create a custom listview in which every single row has a textview and an imageview(which i'll use to check/uncheck the list items) as shown in the following figure:
I want to delete multiple items from the list. How to achieve this ?? Can you please provide any tutorial or reference or link to learn this ??
This is how i created my custom listview with ease:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class DeleteData extends Activity {
Cursor cursor;
ListView lv_delete_data;
static ArrayList<Integer> listOfItemsToDelete;
SQLiteDatabase database;
private Category[] categories;
ArrayList<Category> categoryList;
private ArrayAdapter<Category> listAdapter;
ImageView iv_delete;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_delete_data);
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
manage_reload_list();
listOfItemsToDelete = new ArrayList<Integer>();
iv_delete = (ImageView) findViewById(R.id.imageViewDeleteDataDelete);
iv_delete.setClickable(true);
iv_delete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (listOfItemsToDelete.isEmpty()) {
Toast.makeText(getBaseContext(), "No items selected.",
Toast.LENGTH_SHORT).show();
}
else {
showDialog(
"Warning",
"Are you sure you want to delete these categories ? This will erase all records attached with it.");
}
}
});
lv_delete_data = (ListView) findViewById(R.id.listViewDeleteData);
lv_delete_data.setAdapter(listAdapter);
lv_delete_data.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
ImageView imageView = (ImageView) arg1
.findViewById(R.id.imageViewSingleRowDeleteData);
Category category = (Category) imageView.getTag();
if (category.getChecked() == false) {
imageView.setImageResource(R.drawable.set_check);
listOfItemsToDelete.add(category.getId());
category.setChecked(true);
} else {
imageView.setImageResource(R.drawable.set_basecircle);
listOfItemsToDelete.remove((Integer) category.getId());
category.setChecked(false);
}
}
});
}
private void showDialog(final String title, String message) {
AlertDialog.Builder adb = new Builder(DeleteData.this);
adb.setTitle(title);
adb.setMessage(message);
adb.setIcon(R.drawable.ic_launcher);
String btn = "Ok";
if (title.equals("Warning")) {
btn = "Yes";
adb.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
}
adb.setPositiveButton(btn, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
if (title.equals("Warning")) {
for (int i : listOfItemsToDelete) {
// -------first delete from category table-----
database.delete("category_fields", "cat_id=?",
new String[] { i + "" });
// --------now fetch rec_id where cat_id =
// i-----------------
cursor = database.query("records_data",
new String[] { "rec_id" }, "cat_id=?",
new String[] { i + "" }, null, null, null);
if (cursor.getCount() == 0)
cursor.close();
else {
ArrayList<Integer> al_tmp_rec_id = new ArrayList<Integer>();
while (cursor.moveToNext())
al_tmp_rec_id.add(cursor.getInt(0));
cursor.close();
for (int i1 : al_tmp_rec_id) {
database.delete("records_fields_data",
"rec_id=?", new String[] { i1 + "" });
database.delete("record_tag_relation",
"rec_id=?", new String[] { i1 + "" });
}
// ---------delete from records_data-------
database.delete("records_data", "cat_id=?",
new String[] { i + "" });
cursor.close();
}
}
showDialog("Success",
"Categories, with their records, deleted successfully.");
} else {
database.close();
listOfItemsToDelete.clear();
manage_reload_list();
lv_delete_data.setAdapter(listAdapter);
}
}
});
AlertDialog ad = adb.create();
ad.show();
}
protected void manage_reload_list() {
loadDatabase();
categoryList = new ArrayList<Category>();
// ------first fetch all categories name list-------
cursor = database.query("category", new String[] { "cat_id",
"cat_description" }, null, null, null, null, null);
if (cursor.getCount() == 0) {
Toast.makeText(getBaseContext(), "No categories found.",
Toast.LENGTH_SHORT).show();
cursor.close();
} else {
while (cursor.moveToNext()) {
categories = new Category[] { new Category(cursor.getInt(0),
cursor.getString(1)) };
categoryList.addAll(Arrays.asList(categories));
}
cursor.close();
}
listAdapter = new CategoryArrayAdapter(this, categoryList);
}
static class Category {
String cat_name = "";
int cat_id = 0;
Boolean checked = false;
Category(int cat_id, String name) {
this.cat_name = name;
this.cat_id = cat_id;
}
public int getId() {
return cat_id;
}
public String getCatName() {
return cat_name;
}
public Boolean getChecked() {
return checked;
}
public void setChecked(Boolean checked) {
this.checked = checked;
}
public boolean isChecked() {
return checked;
}
public void toggleChecked() {
checked = !checked;
}
}
static class CategoryViewHolder {
ImageView imageViewCheck;
TextView textViewCategoryName;
public CategoryViewHolder(ImageView iv_check, TextView tv_category_name) {
imageViewCheck = iv_check;
textViewCategoryName = tv_category_name;
}
public ImageView getImageViewCheck() {
return imageViewCheck;
}
public TextView getTextViewCategoryName() {
return textViewCategoryName;
}
}
static class CategoryArrayAdapter extends ArrayAdapter<Category> {
LayoutInflater inflater;
public CategoryArrayAdapter(Context context, List<Category> categoryList) {
super(context, R.layout.single_row_delete_data,
R.id.textViewSingleRowDeleteData, categoryList);
inflater = LayoutInflater.from(context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Category category = (Category) this.getItem(position);
final ImageView imageViewCheck;
final TextView textViewCN;
if (convertView == null) {
convertView = inflater.inflate(R.layout.single_row_delete_data,
null);
imageViewCheck = (ImageView) convertView
.findViewById(R.id.imageViewSingleRowDeleteData);
textViewCN = (TextView) convertView
.findViewById(R.id.textViewSingleRowDeleteData);
convertView.setTag(new CategoryViewHolder(imageViewCheck,
textViewCN));
}
else {
CategoryViewHolder viewHolder = (CategoryViewHolder) convertView
.getTag();
imageViewCheck = viewHolder.getImageViewCheck();
textViewCN = viewHolder.getTextViewCategoryName();
}
imageViewCheck.setFocusable(false);
imageViewCheck.setFocusableInTouchMode(false);
imageViewCheck.setClickable(true);
imageViewCheck.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
ImageView iv = (ImageView) v;
Category category = (Category) iv.getTag();
if (category.getChecked() == false) {
imageViewCheck.setImageResource(R.drawable.set_check);
listOfItemsToDelete.add(category.getId());
category.setChecked(true);
} else {
imageViewCheck
.setImageResource(R.drawable.set_basecircle);
listOfItemsToDelete.remove((Integer) category.getId());
category.setChecked(false);
}
}
});
imageViewCheck.setTag(category);
if (category.getChecked() == true)
imageViewCheck.setImageResource(R.drawable.set_check);
else
imageViewCheck.setImageResource(R.drawable.set_basecircle);
textViewCN.setText(category.getCatName());
return convertView;
}
}
private void loadDatabase() {
database = openOrCreateDatabase("WalletAppDatabase.db",
SQLiteDatabase.OPEN_READWRITE, null);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
finish();
return true;
}
return super.onKeyDown(keyCode, event);
}
}
Anyone who have doubts in this can ask me...
Fisrt of all make a custom adapter and row layout for your listview. Follow this link (click) for that.Then add check-box to each row.You can customize check-box to achieve like the image you have posted.To do that, check this link (click)
After creating your custom listview, you have to get the checked listview row id on checkbox click in custom adapter(inside getview method).When the user click a checkbox you have to get the clicked row id and store into an array list.Lets say, your selected id-array list is "ArrayId" and your listview items array list is "Yourarray". here is the code,
checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
if(isChecked)
{
ArrayId.add(Yourlist.get(position));//add item position to arraylist if checked
}
else
{
ArrayId.remove(Yourlist.get(position));//remove item position from arraylist if unchecked
}
}
}
Then you loop through each id stored in arraylist and delete the entry.Check the code below,
for(int i=0;i<ArrayId.size();i++)
{
Yourlist.remove(ArrayId[i]);
}
Now the items from your listview items array-"Yourlist" will be removed.Then invalidate the listview with updated "Yourlist" array.

Click Event Listeners in a ListActivity [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Android: How to fire onListItemClick in Listactivity with buttons in list?
i have develop one app in which i have make ListActivity in which custome listview are going to display custom item list.all things are going to well but here i am confuse with itemOnClickListner. how can i add onclick listner in listActivity ? because there are not any listview that initialize and i can set listner trough that listview control... i have find out from here but its also not working for me
:Here is Code ::
package com.AppFavorits;
import java.util.ArrayList;
import java.util.Iterator;
import android.app.ListActivity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.Toast;
import com.FavoritesDB.CommentsDataSource;
import com.SharedDB.SharedCommentsDataSource;
public class Favorites extends ListActivity implements OnClickListener {
protected static final String TAG = "Favorites";
CommentsDataSource datasource;
ListView lstFavrowlistv;
float[] rate;
static boolean[] bSelected;
static ArrayList<Comment> alPackagenm;
static ArrayList alAppName;
static String[] strAppnm;
Drawable[] alIcon;
ViewHolder holder;
static int sizeincrement = 1;
private SharedCommentsDataSource ShrdDatasource;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
protected void onResume() {
super.onResume();
datasource = new CommentsDataSource(this);
datasource.open();
ShrdDatasource = new SharedCommentsDataSource(this);
alAppName = datasource.getAllComments();
alPackagenm = datasource.getAllPackage();
Log.i(TAG, "values >>>" + alAppName);
Log.i(TAG, "values >>>" + alPackagenm);
int inc = 0;
alIcon = new Drawable[200];
for (int i = 0; i < alPackagenm.size(); i++) {
Log.i(TAG, "Appname >>>" + GetAllApp.lstpinfo.get(i).pname);
for (int j = 0; j < GetAllApp.lstpinfo.size(); j++) {
if (alPackagenm
.get(i)
.toString()
.equalsIgnoreCase(
GetAllApp.lstpinfo.get(j).pname.toString())) {
alIcon[inc] = GetAllApp.lstpinfo.get(j).icon;
Log.i("TAG", "sqlPackagename"
+ alPackagenm.get(i).toString());
Log.i("TAG", "from getAllapp"
+ GetAllApp.lstpinfo.get(j).pname.toString());
inc++;
}
}
}
ArrayList<RowModel> list = new ArrayList<RowModel>();
ArrayList<Model> Mlist = new ArrayList<Model>();
rate = new float[alAppName.size()];
bSelected = new boolean[alAppName.size()];
Iterator itr = alAppName.iterator();
String strVal = null;
while (itr.hasNext()) {
strVal += itr.next().toString() + ",";
}
int lastIndex = strVal.lastIndexOf(",");
strVal = strVal.substring(0, lastIndex);
System.out.println("Output String is : " + strVal);
String strAr[] = strVal.split(",");
int Appinc = 0;
for (String s : strAr) {
list.add(new RowModel(s));
Appinc += 1;
}
for (String s : strAr) {
Mlist.add(new Model(s));
}
setListAdapter(new RatingAdapter(list, Mlist));
datasource.close();
}
class RowModel {
String label;
float rating = 0.0f;
RowModel(String label) {
this.label = label;
}
public String toString() {
if (rating >= 3.0) {
return (label.toUpperCase());
}
return (label);
}
}
private RowModel getModel(int position) {
return (((RatingAdapter) getListAdapter()).getItem(position));
}
class RatingAdapter extends ArrayAdapter<RowModel> {
private ArrayList<Model> mlist;
boolean[] checkBoxState;
RatingAdapter(ArrayList<RowModel> list, ArrayList<Model> mlist) {
super(Favorites.this, R.layout.outbox_list_item,
R.id.txvxFavrowiconappname, list);
checkBoxState = new boolean[list.size()];
this.mlist = mlist;
}
public View getView(final int position, View convertView,
ViewGroup parent) {
View row = super.getView(position, convertView, parent);
holder = (ViewHolder) row.getTag();
if (convertView == null) {
holder = new ViewHolder(row);
row.setTag(holder);
} else {
row = convertView;
((ViewHolder) row.getTag()).chkbxFavrowsel.setTag(mlist
.get(position));
}
RatingBar.OnRatingBarChangeListener l = new RatingBar.OnRatingBarChangeListener() {
public void onRatingChanged(RatingBar ratingBar, float rating,
boolean fromTouch) {
Integer myPosition = (Integer) ratingBar.getTag();
RowModel model = getModel(myPosition);
model.rating = rating;
rate[position] = rating;
}
};
holder.ratingBar1.setOnRatingBarChangeListener(l);
holder.chkbxFavrowsel
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
Model element = (Model) holder.chkbxFavrowsel
.getTag();
element.setSelected(buttonView.isChecked());
bSelected[position] = isChecked;
element.setsizeInc(sizeincrement);
// if (holder.chkbxFavrowsel.isChecked() ==
// isChecked) {
ShrdDatasource.open();
ShrdDatasource.createComment(alAppName
.get(position).toString(),
"https://play.google.com/store/apps/details?id="
+ alPackagenm.get(position)
.toString(), String
.valueOf(rate[position]));
ShrdDatasource.close();
Log.i(TAG, "Check Position is " + position);
// }
}
});
RowModel model = getModel(position);
ViewHolder holder = (ViewHolder) row.getTag();
holder.ratingBar1.setTag(new Integer(position));
holder.ratingBar1.setRating(model.rating);
holder.imgvFavrowiconappicon.setImageDrawable(alIcon[position]);
holder.txvxFavrowiconappname.setText(alAppName.get(position)
.toString());
holder.chkbxFavrowsel.setChecked(mlist.get(position).isSelected());
holder.chkbxFavrowsel.setTag(mlist.get(position));
return (row);
}
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
ShrdDatasource.close();
}
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "click", Toast.LENGTH_LONG)
.show();
Log.i(TAG, "Click fire");
}
}
Update::
package com.AppFavorits;
import java.util.ArrayList;
import java.util.Iterator;
import android.app.ListActivity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;
import com.FavoritesDB.CommentsDataSource;
import com.SharedDB.SharedCommentsDataSource;
public class Favorites extends ListActivity implements OnClickListener {
protected static final String TAG = "Favorites";
CommentsDataSource datasource;
ListView lstFavrowlistv;
float[] rate;
static boolean[] bSelected;
static ArrayList<Comment> alPackagenm;
static ArrayList alAppName;
static String[] strAppnm;
Drawable[] alIcon;
ViewHolder holder;
static int sizeincrement = 1;
private SharedCommentsDataSource ShrdDatasource;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
protected void onResume() {
super.onResume();
datasource = new CommentsDataSource(this);
datasource.open();
ShrdDatasource = new SharedCommentsDataSource(this);
alAppName = datasource.getAllComments();
alPackagenm = datasource.getAllPackage();
Log.i(TAG, "values >>>" + alAppName);
Log.i(TAG, "values >>>" + alPackagenm);
int inc = 0;
alIcon = new Drawable[200];
for (int i = 0; i < alPackagenm.size(); i++) {
Log.i(TAG, "Appname >>>" + GetAllApp.lstpinfo.get(i).pname);
for (int j = 0; j < GetAllApp.lstpinfo.size(); j++) {
if (alPackagenm
.get(i)
.toString()
.equalsIgnoreCase(
GetAllApp.lstpinfo.get(j).pname.toString())) {
alIcon[inc] = GetAllApp.lstpinfo.get(j).icon;
Log.i("TAG", "sqlPackagename"
+ alPackagenm.get(i).toString());
Log.i("TAG", "from getAllapp"
+ GetAllApp.lstpinfo.get(j).pname.toString());
inc++;
}
}
}
ArrayList<RowModel> list = new ArrayList<RowModel>();
ArrayList<Model> Mlist = new ArrayList<Model>();
rate = new float[alAppName.size()];
bSelected = new boolean[alAppName.size()];
Iterator itr = alAppName.iterator();
String strVal = null;
while (itr.hasNext()) {
strVal += itr.next().toString() + ",";
}
int lastIndex = strVal.lastIndexOf(",");
strVal = strVal.substring(0, lastIndex);
System.out.println("Output String is : " + strVal);
String strAr[] = strVal.split(",");
int Appinc = 0;
for (String s : strAr) {
list.add(new RowModel(s));
Appinc += 1;
}
for (String s : strAr) {
Mlist.add(new Model(s));
}
setListAdapter(new RatingAdapter(list, Mlist));
datasource.close();
}
class RowModel {
String label;
float rating = 0.0f;
RowModel(String label) {
this.label = label;
}
public String toString() {
if (rating >= 3.0) {
return (label.toUpperCase());
}
return (label);
}
}
private RowModel getModel(int position) {
return (((RatingAdapter) getListAdapter()).getItem(position));
}
class RatingAdapter extends ArrayAdapter<RowModel> implements OnClickListener {
private ArrayList<Model> mlist;
boolean[] checkBoxState;
RatingAdapter(ArrayList<RowModel> list, ArrayList<Model> mlist) {
super(Favorites.this, R.layout.outbox_list_item,
R.id.txvxFavrowiconappname, list);
checkBoxState = new boolean[list.size()];
this.mlist = mlist;
}
public View getView(final int position, View convertView,
ViewGroup parent) {
View row = super.getView(position, convertView, parent);
holder = (ViewHolder) row.getTag();
if (convertView == null) {
holder = new ViewHolder(row);
row.setTag(holder);
} else {
row = convertView;
((ViewHolder) row.getTag()).chkbxFavrowsel.setTag(mlist
.get(position));
}
RatingBar.OnRatingBarChangeListener l = new RatingBar.OnRatingBarChangeListener() {
public void onRatingChanged(RatingBar ratingBar, float rating,
boolean fromTouch) {
Integer myPosition = (Integer) ratingBar.getTag();
RowModel model = getModel(myPosition);
model.rating = rating;
rate[position] = rating;
}
};
holder.ratingBar1.setOnRatingBarChangeListener(l);
holder.chkbxFavrowsel
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
Model element = (Model) holder.chkbxFavrowsel
.getTag();
element.setSelected(buttonView.isChecked());
bSelected[position] = isChecked;
element.setsizeInc(sizeincrement);
// if (holder.chkbxFavrowsel.isChecked() ==
// isChecked) {
ShrdDatasource.open();
ShrdDatasource.createComment(alAppName
.get(position).toString(),
"https://play.google.com/store/apps/details?id="
+ alPackagenm.get(position)
.toString(), String
.valueOf(rate[position]));
ShrdDatasource.close();
Log.i(TAG, "Check Position is " + position);
// }
}
});
RowModel model = getModel(position);
ViewHolder holder = (ViewHolder) row.getTag();
holder.ratingBar1.setTag(new Integer(position));
holder.ratingBar1.setRating(model.rating);
holder.imgvFavrowiconappicon.setImageDrawable(alIcon[position]);
holder.txvxFavrowiconappname.setText(alAppName.get(position)
.toString());
holder.chkbxFavrowsel.setChecked(mlist.get(position).isSelected());
holder.chkbxFavrowsel.setTag(mlist.get(position));
return (row);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),
"hey this ", Toast.LENGTH_SHORT).show();
Log.i(TAG, "Click this");
}
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
ShrdDatasource.close();
}
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "click", Toast.LENGTH_LONG)
.show();
Log.i(TAG, "Click fire");
}
}
Update3
package com.AppFavorits;
import java.util.ArrayList;
import java.util.Iterator;
import android.app.Activity;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.Toast;
import com.FavoritesDB.CommentsDataSource;
import com.SharedDB.SharedCommentsDataSource;
public class Favorites extends Activity implements OnClickListener, OnItemClickListener {
protected static final String TAG = "Favorites";
CommentsDataSource datasource;
ListView lstFavrowlistv;
float[] rate;
static boolean[] bSelected;
static ArrayList<Comment> alPackagenm;
static ArrayList alAppName;
static String[] strAppnm;
Drawable[] alIcon;
ViewHolder holder;
static int sizeincrement = 1;
private SharedCommentsDataSource ShrdDatasource;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.favorites);
lstFavrowlistv = (ListView)findViewById(R.id.lstFavrowlistv);
lstFavrowlistv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> myAdapter, View myView, int myItemInt, long mylng) {
Toast.makeText(getApplicationContext(), "click", Toast.LENGTH_LONG)
.show();
Log.i(TAG, "Click fire");
}
});
}
#Override
protected void onResume() {
super.onResume();
datasource = new CommentsDataSource(this);
datasource.open();
ShrdDatasource = new SharedCommentsDataSource(this);
alAppName = datasource.getAllComments();
alPackagenm = datasource.getAllPackage();
Log.i(TAG, "values >>>" + alAppName);
Log.i(TAG, "values >>>" + alPackagenm);
int inc = 0;
alIcon = new Drawable[200];
for (int i = 0; i < alPackagenm.size(); i++) {
Log.i(TAG, "Appname >>>" + GetAllApp.lstpinfo.get(i).pname);
for (int j = 0; j < GetAllApp.lstpinfo.size(); j++) {
if (alPackagenm
.get(i)
.toString()
.equalsIgnoreCase(
GetAllApp.lstpinfo.get(j).pname.toString())) {
alIcon[inc] = GetAllApp.lstpinfo.get(j).icon;
Log.i("TAG", "sqlPackagename"
+ alPackagenm.get(i).toString());
Log.i("TAG", "from getAllapp"
+ GetAllApp.lstpinfo.get(j).pname.toString());
inc++;
}
}
}
ArrayList<RowModel> list = new ArrayList<RowModel>();
ArrayList<Model> Mlist = new ArrayList<Model>();
rate = new float[alAppName.size()];
bSelected = new boolean[alAppName.size()];
Iterator itr = alAppName.iterator();
String strVal = null;
while (itr.hasNext()) {
strVal += itr.next().toString() + ",";
}
int lastIndex = strVal.lastIndexOf(",");
strVal = strVal.substring(0, lastIndex);
System.out.println("Output String is : " + strVal);
String strAr[] = strVal.split(",");
int Appinc = 0;
for (String s : strAr) {
list.add(new RowModel(s));
Appinc += 1;
}
for (String s : strAr) {
Mlist.add(new Model(s));
}
lstFavrowlistv.setAdapter(new RatingAdapter(list, Mlist));
datasource.close();
}
class RowModel {
String label;
float rating = 0.0f;
RowModel(String label) {
this.label = label;
}
public String toString() {
if (rating >= 3.0) {
return (label.toUpperCase());
}
return (label);
}
}
private RowModel getModel(int position) {
return (((RatingAdapter) lstFavrowlistv.getAdapter()).getItem(position));
}
class RatingAdapter extends ArrayAdapter<RowModel> implements OnClickListener {
private ArrayList<Model> mlist;
boolean[] checkBoxState;
RatingAdapter(ArrayList<RowModel> list, ArrayList<Model> mlist) {
super(Favorites.this, R.layout.outbox_list_item,
R.id.txvxFavrowiconappname, list);
checkBoxState = new boolean[list.size()];
this.mlist = mlist;
}
public View getView(final int position, View convertView,
ViewGroup parent) {
View row = super.getView(position, convertView, parent);
holder = (ViewHolder) row.getTag();
if (convertView == null) {
holder = new ViewHolder(row);
row.setTag(holder);
} else {
row = convertView;
((ViewHolder) row.getTag()).chkbxFavrowsel.setTag(mlist
.get(position));
}
RatingBar.OnRatingBarChangeListener l = new RatingBar.OnRatingBarChangeListener() {
public void onRatingChanged(RatingBar ratingBar, float rating,
boolean fromTouch) {
Integer myPosition = (Integer) ratingBar.getTag();
RowModel model = getModel(myPosition);
model.rating = rating;
rate[position] = rating;
}
};
holder.ratingBar1.setOnRatingBarChangeListener(l);
holder.chkbxFavrowsel
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
Model element = (Model) holder.chkbxFavrowsel
.getTag();
element.setSelected(buttonView.isChecked());
bSelected[position] = isChecked;
element.setsizeInc(sizeincrement);
// if (holder.chkbxFavrowsel.isChecked() ==
// isChecked) {
ShrdDatasource.open();
ShrdDatasource.createComment(alAppName
.get(position).toString(),
"https://play.google.com/store/apps/details?id="
+ alPackagenm.get(position)
.toString(), String
.valueOf(rate[position]));
ShrdDatasource.close();
Log.i(TAG, "Check Position is " + position);
// }
}
});
RowModel model = getModel(position);
ViewHolder holder = (ViewHolder) row.getTag();
holder.ratingBar1.setTag(new Integer(position));
holder.ratingBar1.setRating(model.rating);
holder.imgvFavrowiconappicon.setImageDrawable(alIcon[position]);
holder.txvxFavrowiconappname.setText(alAppName.get(position)
.toString());
holder.chkbxFavrowsel.setChecked(mlist.get(position).isSelected());
holder.chkbxFavrowsel.setTag(mlist.get(position));
return (row);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(),
"hey this ", Toast.LENGTH_SHORT).show();
Log.i(TAG, "Click this");
}
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
ShrdDatasource.close();
}
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "click", Toast.LENGTH_LONG)
.show();
Log.i(TAG, "Click fire");
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "click", Toast.LENGTH_LONG)
.show();
Log.i(TAG, "Click fire");
}
}
use getListview() in list Activity to get List..........
in Oncreate
ListView lv = getListView();
http://www.mkyong.com/android/android-listview-example/
this link has both ways
1- overriding onListItemClick(
2- Setting you listener..
Try this way..
ListView lv = getListView();
lv. storelist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
}
this are help you.
Thanks
Override the function onlistitemclick() for this. Here the integer position represents the postion of item that you had pressed
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
.......
}
Try this one
getListView().setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
// TODO Auto-generated method stub
}
});

Categories

Resources