After selecting the header checkbox all listview item checkbox not selected.
Selected listview checkbox items are not moved from list1 to list2.
Below is the full code
Home Activity class
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class HomeAct extends Activity {
List<DocItem> docDet1 = new ArrayList<DocItem>();
List<DocItem> docDet2 = new ArrayList<DocItem>();
ListView lv1, lv2;
Button btn1;
DocDetAdapter adapter1, adapter2;
int n = 0;
int marksValue;
int value = 0;
CheckBox boxheader;
ArrayList<Boolean> positionArray;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home_act);
lv1 = (ListView) findViewById(R.id.lv_det1);
lv2 = (ListView) findViewById(R.id.lv_det2);
btn1 = (Button) findViewById(R.id.btn1);
boxheader = (CheckBox)findViewById(R.id.checkBoxHeader);
adapter1 = new DocDetAdapter(1);
adapter2 = new DocDetAdapter(2);
docDet1.add(new DocItem("1", "john", 20));
docDet1.add(new DocItem("2", "karan", 10));
docDet1.add(new DocItem("3", "james", 5));
docDet1.add(new DocItem("4", "shaun", 60));
docDet1.add(new DocItem("5", "jack", 50));
docDet1.add(new DocItem("6", "sam", 30));
docDet1.add(new DocItem("7", "tony", 6));
docDet1.add(new DocItem("8", "mark", 42));
lv1.setAdapter(adapter1);
lv2.setAdapter(adapter2);
positionArray = new ArrayList<Boolean>(docDet1.size());
for (int i = 0; i < docDet1.size(); i++) {
positionArray.add(false);
}
boxheader.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
int itemsCount = lv1.getChildCount();
for (int i = 0; i < itemsCount; i++) {
View view = lv1.getChildAt(i);
CheckBox checkBox = (CheckBox) view
.findViewById(R.id.checkBoxRow);
checkBox.setChecked(true);
}
} else {
int itemsCount = lv1.getChildCount();
for (int i = 0; i < itemsCount; i++) {
View view = lv1.getChildAt(i);
CheckBox checkBox = (CheckBox) view
.findViewById(R.id.checkBoxRow);
checkBox.setChecked(false);
}
}
}
});
btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
int itemsCount = lv1.getChildCount();
for (int i = 0; i < itemsCount; i++) {
View view = lv1.getChildAt(i);
CheckBox checkBox = (CheckBox) view
.findViewById(R.id.checkBoxRow);
if (checkBox.isChecked()) {
System.out.println("HomeAct.onCreate(...).new OnClickListener() {...}.onClick() -- 1111 " + i);
System.out.println("HomeAct.onCreate(...).new OnClickListener() {...}.onClick() -- 2222 " + docDet1.size());
if (docDet1.size() == 1) {
new AlertDialog.Builder(HomeAct.this)
.setTitle("Attention!")
.setMessage("Last name")
.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
#Override
public void onClick(
DialogInterface dialog,
int which) {
docDet1.remove(0);
docDet2.add(new DocItem(docDet1.get(0).docNo, docDet1.get(0).name, docDet1.get(0).marks));
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(
DialogInterface dialog,
int which) {
}
}).show();
return;
}
docDet2.add(new DocItem(docDet1.get(i).docNo, docDet1.get(i).name, docDet1.get(i).marks));
docDet1.remove(i);
adapter2.notifyDataSetChanged();
adapter1.notifyDataSetChanged();
} else {
System.out.println("HomeAct.onCreate(...).new OnClickListener() {...}.onClick() -- 3333 none are checked ");
Toast.makeText(HomeAct.this, "Please select atleast one name", Toast.LENGTH_LONG).show();
}
}
}
});
}
DocItem findDocItem(String name) {
for (DocItem item : docDet2) {
if (item.name.equals(name)) {
return item;
}
}
return null;
}
DocItem findDocItem2(String name) {
for (DocItem item : docDet1) {
if (item.name.equals(name)) {
return item;
}
}
return null;
}
private class DocDetAdapter extends BaseAdapter {
int mode; // 1 or 2
public DocDetAdapter(int mode) {
this.mode = mode;
}
#Override
public int getCount() {
if (mode == 1)
return docDet1.size();
else
return docDet2.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
LayoutInflater li = getLayoutInflater();
if (convertView == null)
convertView = li.inflate(R.layout.row_det, null);
TextView tvName = (TextView) convertView
.findViewById(R.id.tv_name);
TextView tvNo = (TextView) convertView.findViewById(R.id.tv_no);
TextView tvMarks = (TextView) convertView.findViewById(R.id.tv_marks);
CheckBox box = (CheckBox)convertView.findViewById(R.id.checkBoxRow);
DocItem invItem;
if (mode == 1)
invItem = docDet1.get(position);
else
invItem = docDet2.get(position);
tvNo.setText(invItem.docNo);
tvName.setText(invItem.name);
tvMarks.setText(invItem.marks + "");
box.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
positionArray.set(position, true);
} else {
positionArray.set(position, false);
}
}
});
box.setChecked(positionArray.get(position));
return convertView;
}
}
}
DocItem class
public class DocItem {
public String docNo, name;
public Integer marks;
public DocItem(String docNo, String name, Integer marks) {
super();
this.docNo = docNo;
this.name = name;
this.marks = marks;
}
}
home_act.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Button
android:id="#+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:ems="3"
android:text="Add" />
<TextView
android:id="#+id/textView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:gravity="center"
android:text="list 1"
android:textSize="20sp"
android:textStyle="bold" >
</TextView>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/row_bg_transparent_white"
android:gravity="center_vertical"
android:orientation="horizontal" >
<TextView
android:id="#+id/tv_tv_no"
style="#android:style/TextAppearance.Medium"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="5"
android:gravity="center_vertical"
android:padding="10dp"
android:text="Sl no"
android:textStyle="bold" />
<TextView
android:id="#+id/tv_name"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:ems="10"
android:gravity="center_vertical"
android:text="Name"
android:textSize="15sp"
android:textStyle="bold" />
<TextView
android:id="#+id/tv_marks"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:ems="10"
android:gravity="center_vertical"
android:paddingRight="3dp"
android:text="Marks"
android:textSize="16sp"
android:textStyle="bold" />
<CheckBox
android:id="#+id/checkBoxHeader"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Select all" />
</LinearLayout>
<ListView
android:id="#+id/lv_det1"
android:layout_width="fill_parent"
android:layout_height="200dp"
android:layout_marginTop="10dp" />
<TextView
android:id="#+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:gravity="center"
android:text="list 2"
android:textSize="20sp"
android:textStyle="bold" >
</TextView>
<ListView
android:id="#+id/lv_det2"
android:layout_width="fill_parent"
android:layout_height="250dp" />
</LinearLayout>
row_det.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<View
android:id="#+id/v_doc_seperator"
android:layout_width="match_parent"
android:layout_height="4dp"
android:background="#color/blue"
android:visibility="gone" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#color/row_bg_transparent_white"
android:gravity="center_vertical"
android:orientation="horizontal" >
<TextView
android:id="#+id/tv_no"
style="#android:style/TextAppearance.Medium"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="5"
android:gravity="center_vertical"
android:padding="10dp"
android:text="Sl no"
android:textStyle="bold" />
<TextView
android:id="#+id/tv_name"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:ems="10"
android:gravity="center_vertical"
android:text="Name"
android:textSize="15sp"
android:textStyle="bold" />
<TextView
android:id="#+id/tv_marks"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:ems="10"
android:gravity="center_vertical"
android:paddingRight="3dp"
android:text="Marks"
android:textSize="16sp"
android:textStyle="bold" />
<CheckBox
android:id="#+id/checkBoxRow"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
</LinearLayout>
</LinearLayout>
Please find the below screenshots
If I select header checkbox(select all), only first five rows are selected
Remainig rows are not selected
If I select row 2 and row 3 and click on add I got wrong output(refer last screenshot)
row 2 and row 4 are added in list2 (but correct output is row 2 and row 3 should be added) after clicking on add all the checkboxes should be unchecked.
Please help me thanks in advance.
Try this:
public class HomeAct extends Activity {
List<DocItem> docDet1 = new ArrayList<DocItem>();
List<DocItem> docDet2 = new ArrayList<DocItem>();
ListView lv1, lv2;
Button btn1;
DocDetAdapter adapter1, adapter2;
int n = 0;
int marksValue;
int value = 0;
CheckBox boxheader;
ArrayList<Boolean> positionArray;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home_act);
lv1 = (ListView) findViewById(R.id.lv_det1);
lv2 = (ListView) findViewById(R.id.lv_det2);
btn1 = (Button) findViewById(R.id.btn1);
boxheader = (CheckBox)findViewById(R.id.checkBoxHeader);
adapter1 = new DocDetAdapter(1);
adapter2 = new DocDetAdapter(2);
docDet1.add(new DocItem("1", "john", 20));
docDet1.add(new DocItem("2", "karan", 10));
docDet1.add(new DocItem("3", "james", 5));
docDet1.add(new DocItem("4", "shaun", 60));
docDet1.add(new DocItem("5", "jack", 50));
docDet1.add(new DocItem("6", "sam", 30));
docDet1.add(new DocItem("7", "tony", 6));
docDet1.add(new DocItem("8", "mark", 42));
lv1.setAdapter(adapter1);
lv2.setAdapter(adapter2);
positionArray = new ArrayList<Boolean>(docDet1.size());
for (int i = 0; i < docDet1.size(); i++) {
positionArray.add(false);
}
boxheader.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
/* int itemsCount = lv1.getChildCount();
for (int i = 0; i < itemsCount; i++) {
View view = lv1.getChildAt(i);
CheckBox checkBox = (CheckBox) view.findViewById(R.id.checkBoxRow);
checkBox.setChecked(true);
} */
// Update DataSet instead of view
for (int i = 0; i < docDet1.size(); i++){
positionArray.set(i, true);
}
} else {
/* int itemsCount = lv1.getChildCount();
for (int i = 0; i < itemsCount; i++) {
View view = lv1.getChildAt(i);
CheckBox checkBox = (CheckBox) view.findViewById(R.id.checkBoxRow);
checkBox.setChecked(false);
} */
// Update DataSet instead of view
for (int i = 0; i < docDet1.size(); i++){
positionArray.set(i, false);
}
}
// Update ListView after dataSet updated.
adapter1.notifyDataSetChanged();
}
});
btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
/* int itemsCount = lv1.getChildCount(); */
// Get items from end to beginning of list.
// Otherwise position may be wrong after remove item.
for (int i = docDet1.size() - 1; i >= 0; i--) {
/* View view = lv1.getChildAt(i);
CheckBox checkBox = (CheckBox) view.findViewById(R.id.checkBoxRow);
if (checkBox.isChecked()) { */
if(positionArray.get(i)) {
System.out.println("HomeAct.onCreate(...).new OnClickListener() {...}.onClick() -- 1111 " + i);
System.out.println("HomeAct.onCreate(...).new OnClickListener() {...}.onClick() -- 2222 " + docDet1.size());
if (docDet1.size() == 1) {
new AlertDialog.Builder(HomeAct.this)
.setTitle("Attention!")
.setMessage("Last name")
.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
#Override
public void onClick(
DialogInterface dialog,
int which) {
docDet1.remove(0);
docDet2.add(new DocItem(docDet1.get(0).docNo, docDet1.get(0).name, docDet1.get(0).marks));
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(
DialogInterface dialog,
int which) {
}
}).show();
return;
}
docDet2.add(0, new DocItem(docDet1.get(i).docNo, docDet1.get(i).name, docDet1.get(i).marks));
docDet1.remove(i);
/* adapter2.notifyDataSetChanged();
adapter1.notifyDataSetChanged(); */
} else {
System.out.println("HomeAct.onCreate(...).new OnClickListener() {...}.onClick() -- 3333 none are checked ");
Toast.makeText(HomeAct.this, "Please select atleast one name", Toast.LENGTH_LONG).show();
}
}
// Reset all CheckBox data
for (int i = 0; i < positionArray.size(); i++){
positionArray.set(i, false);
}
// Update ListViews after all data updated.
adapter2.notifyDataSetChanged();
adapter1.notifyDataSetChanged();
}
});
}
DocItem findDocItem(String name) {
for (DocItem item : docDet2) {
if (item.name.equals(name)) {
return item;
}
}
return null;
}
DocItem findDocItem2(String name) {
for (DocItem item : docDet1) {
if (item.name.equals(name)) {
return item;
}
}
return null;
}
private class DocDetAdapter extends BaseAdapter {
int mode; // 1 or 2
public DocDetAdapter(int mode) {
this.mode = mode;
}
#Override
public int getCount() {
if (mode == 1)
return docDet1.size();
else
return docDet2.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater li = getLayoutInflater();
if (convertView == null) convertView = li.inflate(R.layout.row_det, null);
TextView tvName = (TextView) convertView.findViewById(R.id.tv_name);
TextView tvNo = (TextView) convertView.findViewById(R.id.tv_no);
TextView tvMarks = (TextView) convertView.findViewById(R.id.tv_marks);
CheckBox box = (CheckBox)convertView.findViewById(R.id.checkBoxRow);
DocItem invItem;
if (mode == 1)
invItem = docDet1.get(position);
else
invItem = docDet2.get(position);
tvNo.setText(invItem.docNo);
tvName.setText(invItem.name);
tvMarks.setText(invItem.marks + "");
box.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked) {
positionArray.set(position, true);
} else {
positionArray.set(position, false);
}
}
});
box.setChecked(positionArray.get(position));
return convertView;
}
}
}
Hope this help!
Because after checked you are adding on the array that contain in adapter and on scrolling it will refresh. So you should use interface here after checked or unchecked you should add status in main class and then notify your adapter and invalidate your listview.
Related
I am facing two issues.
Radio buttons in radiogroup loosing state: when I click yes or no and scroll down the list view it looses the radiobutton value which is checked. I tried many ways to fix it but unable to achieve.
Submit button validation(Please refer image four): list of questions user should select either yes or no before clicking on submit button, if user click on submit button without selecting either yes or no it should them a toast message. all the questions should be selected with either yes or no. More specific each radiogroup should give me yes or no, not empty string.
Thanks in advance.
Custom Adapter
public class CustomAdapter extends BaseAdapter {
Context context;
String[] questionsList;
LayoutInflater inflter;
public static ArrayList<String> selectedAnswers;
public CustomAdapter(Context applicationContext, String[] questionsList) {
this.context = context;
this.questionsList = questionsList;
selectedAnswers = new ArrayList<>();
for (int i = 0; i < questionsList.length; i++) {
selectedAnswers.add("");
}
inflter = (LayoutInflater.from(applicationContext));
}
#Override
public int getCount() {
return questionsList.length;
}
#Override
public Object getItem(int i) {
return i;
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public int getViewTypeCount() {
return questionsList.length;
}
#Override
public int getItemViewType(int i) {
return i;
}
#Override
public View getView(final int i, View view, ViewGroup viewGroup) {
view = inflter.inflate(R.layout.list_items, null);
TextView question = (TextView) view.findViewById(R.id.question);
final RadioButton yes = (RadioButton) view.findViewById(R.id.yes);
final RadioButton no = (RadioButton) view.findViewById(R.id.no);
final RadioGroup rg = (RadioGroup) view.findViewById(R.id.radio_group);
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (yes.isChecked()) {
yes.setBackgroundColor(Color.GREEN);
no.setBackgroundColor(Color.BLACK);
}
if (no.isChecked()){
no.setBackgroundColor(Color.rgb(255,165,0));
yes.setBackgroundColor(Color.BLACK);
}
}
});
yes.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked)
selectedAnswers.set(i, "1");
}
});
no.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked)
selectedAnswers.set(i, "2");
}
});
question.setText(questionsList[i]);
return view;
}
Main Activity
public class MainActivity extends AppCompatActivity {
ListView simpleList;
String[] questions;
Button submit,submit1;
FileOutputStream fstream;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
questions = getResources().getStringArray(R.array.questions);
simpleList = (ListView) findViewById(R.id.simpleListView);
View footerView = getLayoutInflater().inflate(R.layout.footer,null);
submit = (Button) footerView.findViewById(R.id.submit1);
simpleList.addFooterView(footerView);
View headerView = getLayoutInflater().inflate(R.layout.header, null);
simpleList.addHeaderView(headerView);
CustomAdapter customAdapter = new CustomAdapter(getApplicationContext(), questions);
simpleList.setAdapter(customAdapter);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String message = "";
for (int i = 0; i < CustomAdapter.selectedAnswers.size(); i++) {
message = message + "\n" + (i + 1) + " " + CustomAdapter.selectedAnswers.get(i);
}
try {
fstream = openFileOutput("user_answer", Context.MODE_PRIVATE);
fstream.write(message.getBytes());
fstream.close();
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
Intent inent = new Intent(v.getContext(), DetailsActivity.class);
startActivity(inent);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
XML main layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#color/Black"
android:padding="10dp">
<RelativeLayout
android:id="#+id/main"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center"
android:background="#drawable/round_relativelayout"
>
<ListView
android:id="#+id/simpleListView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:divider="#color/Black"
android:dividerHeight="1dp"
android:footerDividersEnabled="false"
/>
</RelativeLayout>
List item XML
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:background="#color/LightGrey">
<!-- TextView for displaying question-->
<TextView
android:id="#+id/question"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:padding="#dimen/activity_horizontal_margin"
android:textColor="#000"
android:textSize="30dp"
android:text="Which is your most favorite?"
/>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:id="#+id/main">
<RadioGroup
android:id="#+id/radio_group"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="horizontal">
<RadioButton
android:id="#+id/yes"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="20dp"
android:background="#color/Black"
android:button="#null"
android:paddingHorizontal="30dp"
android:paddingVertical="5dp"
android:text="YES"
android:textColor="#color/White"
android:textSize="50dp" />
<RadioButton
android:id="#+id/no"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:background="#color/Black"
android:button="#null"
android:paddingHorizontal="30dp"
android:paddingVertical="5dp"
android:text="NO"
android:textColor="#color/White"
android:textSize="50dp" />
</RadioGroup>
</FrameLayout>
Image oneImage twoImage threeImage four with submit button
Try the following:
1) MainActivity_.class:-----
public class MainActivity_ extends AppCompatActivity {
private ListView lv;
private CustomAdapter customAdapter;
private String[] questions;
private Button submit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout8);
questions = new String[10];
for(int i = 0 ; i<10 ; i++){
questions[i] = "Q " + i;
}
lv = (ListView) findViewById(R.id.lv);
customAdapter = new CustomAdapter(getApplicationContext() , questions);
lv.setAdapter(customAdapter);
submit = (Button) findViewById(R.id.submit);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
boolean found_unanswered = false;
if(customAdapter != null){
for(int i = 0 ; i<customAdapter.getSelectedAnswers().size() ; i++){
if(customAdapter.getSelectedAnswers().get(i).equals("3")){
found_unanswered = true;
break;
}
}
}
if(!found_unanswered){
Toast.makeText(getApplicationContext() , "All Answered" , Toast.LENGTH_LONG).show();
//Go to other activity
}
}
});
}
}
2) CustomAdapter.class:------
public class CustomAdapter extends BaseAdapter {
Context context;
String[] questionsList;
LayoutInflater inflter;
public ArrayList<String> selectedAnswers;
public CustomAdapter(Context applicationContext, String[] questionsList) {
this.context = context;
this.questionsList = questionsList;
selectedAnswers = new ArrayList<>();
for (int i = 0; i < questionsList.length; i++) {
selectedAnswers.add("3");
}
inflter = (LayoutInflater.from(applicationContext));
}
#Override
public int getCount() {
return questionsList.length;
}
#Override
public Object getItem(int i) {
return questionsList[i];
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public int getViewTypeCount() {
return questionsList.length;
}
#Override
public int getItemViewType(int i) {
return i;
}
#Override
public View getView(final int i, View convertView, ViewGroup viewGroup) {
View view = convertView;
if (convertView == null) {
if (inflter != null) {
view = inflter.inflate(R.layout.list_items, null);
}
}
TextView question = (TextView) view.findViewById(R.id.question);
question.setText(questionsList[i]);
// initialize/ restore UI Radio Button State
final RadioGroup rg = (RadioGroup) view.findViewById(R.id.radio_group);
RadioButton rb_yes = (RadioButton) rg.findViewById(R.id.yes);
RadioButton rb_no = (RadioButton) rg.findViewById(R.id.no);
if(selectedAnswers.get(i).equals("1")){
rg.check(R.id.yes);
rb_yes.setBackgroundColor(Color.GREEN);
rb_no.setBackgroundColor(Color.GRAY);
}else if(selectedAnswers.get(i).equals("2")){
rg.check(R.id.no);
rb_yes.setBackgroundColor(Color.GRAY);
rb_no.setBackgroundColor(Color.BLACK);
}else{
// no answer.
rb_yes.setBackgroundColor(Color.GRAY);
rb_no.setBackgroundColor(Color.GRAY);
}
rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
RadioButton rb_yes = (RadioButton) group.findViewById(R.id.yes);
RadioButton rb_no = (RadioButton) group.findViewById(R.id.no);
switch (checkedId){
case R.id.yes:
rb_yes.setBackgroundColor(Color.GREEN);
rb_no.setBackgroundColor(Color.GRAY);
selectedAnswers.set(i, "1");
break;
case R.id.no:
rb_yes.setBackgroundColor(Color.GRAY);
rb_no.setBackgroundColor(Color.BLACK);
selectedAnswers.set(i, "2");
break;
}
}
});
return view;
}
public List<String> getSelectedAnswers(){
return selectedAnswers;
}
}
3) layout8.xml:------
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:weightSum="100">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="80"
android:id="#+id/lv">
</ListView>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/lv"
android:layout_weight="20"
android:text="Submit"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:id="#+id/submit"/>
</LinearLayout>
4) list_items.xml:-----
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical">
<!-- TextView for displaying question-->
<TextView
android:id="#+id/question"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textColor="#000"
android:textSize="30dp"
android:text="Which is your most favorite?"
/>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
android:id="#+id/main">
<RadioGroup
android:id="#+id/radio_group"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="horizontal">
<RadioButton
android:id="#+id/yes"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="20dp"
android:button="#null"
android:paddingHorizontal="30dp"
android:paddingVertical="5dp"
android:text="YES"
android:textSize="50dp" />
<RadioButton
android:id="#+id/no"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:button="#null"
android:paddingHorizontal="30dp"
android:paddingVertical="5dp"
android:text="NO"
android:textSize="50dp" />
</RadioGroup>
</FrameLayout>
</LinearLayout>
Try this.
Use ViewHolder so it does not lose the data set
Custom Adapter class
#Override
public View getView(final int i, View view, ViewGroup viewGroup) {
ViewHolder viewHolder;
if(view == null){
view = inflter.inflate(R.layout.list_items, null);
viewHolder = new ViewHolder();
ViewHoldwe.question = (TextView) view.findViewById(R.id.question);
viewHolder.yes = (RadioButton) view.findViewById(R.id.yes);
viewHolder.no = (RadioButton) view.findViewById(R.id.no);
viewHolder.rg = (RadioGroup) view.findViewById(R.id.radio_group);
view.setTag(viewHolder)
}else{
viewHolder = (ViewHolder) view.getTag();
viewHolder.rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (viewHolder.yes.isChecked()) {
viewHolder.yes.setBackgroundColor(Color.GREEN);
viewHolder.no.setBackgroundColor(Color.BLACK);
}
if (viewHolder.no.isChecked()){
viewHolder.no.setBackgroundColor(Color.rgb(255,165,0));
viewHolder.yes.setBackgroundColor(Color.BLACK);
}
}
});
viewHolder.yes.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked)
selectedAnswers.set(i, "1");
}
});
viewHolder.no.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (isChecked)
selectedAnswers.set(i, "2");
}
});
question.setText(questionsList[i]);
}
return view;
}
Make a private inner class
private class ViewHolder{
RadioButton yes;
TextView question;
RadioButton no ;
RadioGroup rg;
}
I used RelativeLayout for my ListView.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="6dip" >
<CheckBox
android:id="#+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:focusable="false"
android:focusableInTouchMode="false"
android:text="CheckBox" />
<TextView
android:id="#+id/test"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/checkBox1"
android:layout_alignBottom="#+id/checkBox1"
android:layout_toRightOf="#+id/checkBox1"
android:text="TextView" />
</RelativeLayout>
Here is my ListView code,
private void displayList(){
ArrayList<String> diyListArray = new ArrayList<String>();
diyListArray.add("1");
diyListArray.add("2");
diyListArray.add("3");
diyListArray.add("4");
diyListArray.add("5");
diyListArray.add("6");
diyListArray.add("7");
listAdapter = new ArrayAdapter<String>(this, R.layout.selectrow, R.id.test, diyListArray);
diyList.setAdapter( listAdapter );
}
We can see here that I used ArrayAdapter with resource id of TextView.
I am able to display the checkboxes and their corresponding texts.
How can I get user selected texts from checkboxes?
Try the following:
Demo10.class:----
public class Demo10 extends AppCompatActivity implements Listener {
private ListView lv;
private boolean[] state_ = new boolean[4];
private String[] text_ = new String[4];
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.demo11);
for(int i = 0 ; i<4 ; i++) {
state_[i] = false;
text_[i] = "text"+i;
}
lv = (ListView) findViewById(R.id.lv);
lv.setAdapter(new ItemAdapter(Demo10.this , this));// This includes a Listener that listens to onCheckBoxStateChanges.
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { // used to handle ListView onItemClicks and how they should affect the corresponding checkBox
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
CheckBox cb = view.findViewById(R.id.cb);
cb.setChecked(!cb.isChecked());
displayCheckBoxStateText();
}
});
}
private void displayCheckBoxStateText(){
for(int i = 0 ; i<4 ; i++){
Log.e("CheckBox", text_[i]+" : " + state_[i]);
}
}
#Override
public void checkBox1(boolean state) {
state_[0] = state;
displayCheckBoxStateText();
}
#Override
public void checkBox2(boolean state) {
state_[1] = state;
displayCheckBoxStateText();
}
#Override
public void checkBox3(boolean state) {
state_[2] = state;
displayCheckBoxStateText();
}
#Override
public void checkBox4(boolean state) {
state_[3] = state;
displayCheckBoxStateText();
}
}
ItemAdapter.class:-----
public class ItemAdapter extends BaseAdapter {
private Context mContext;
private LayoutInflater layoutInflater;
private Listener callback;
public ItemAdapter(Context c , Listener l) {
mContext = c;
callback = l;
layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return s.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View convertView, ViewGroup parent) {
CheckBox cb;
View view = convertView;
if (convertView == null) {
if (layoutInflater != null) {
view = layoutInflater.inflate(R.layout.demo10, null);
}
}
cb = view.findViewById(R.id.cb);
cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
switch (position) {
case 0:
callback.checkBox1(isChecked);
break;
case 1:
callback.checkBox2(isChecked);
break;
case 2:
callback.checkBox3(isChecked);
break;
case 3:
callback.checkBox4(isChecked);
break;
default:
break;
}
}
});
cb.setText(s[position]);
return view;
}
private String[] s = {
"test1",
"test2",
"test3",
"test4"
};
}
Listener interface:----
public interface Listener {
public void checkBox1(boolean state);
public void checkBox2(boolean state);
public void checkBox3(boolean state);
public void checkBox4(boolean state);
}
demo10.xml:----
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="6dip" >
<CheckBox
android:id="#+id/cb"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:focusable="false"
android:focusableInTouchMode="false"
android:text="" />
</RelativeLayout>
demo11.xml:-----
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/lv">
</ListView>
</android.support.constraint.ConstraintLayout>
Make choice mode first
listview.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
I am making a button by clicking on it you can retrieve all the items you checked
button.setOnClickListener(this);
#Override
public void onClick(View v) {
SparseBooleanArray checked = listview.getCheckedItemPositions();
ArrayList<String> selectedItems = new ArrayList<String>();
for (int i = 0; i < checked.size(); i++) {
int position = checked.keyAt(i);
if (checked.valueAt(i))
selectedItems.add(listAdapter.getItem(position));
}
}
here you get all the items checked in your selectedItems ArrayList.
You can override getView() of ArrayAdapter and handles views by yourself. Replace:
listAdapter = new ArrayAdapter<String>(this, R.layout.selectrow, R.id.test, diyListArray);
with
listAdapter = new ArrayAdapter<String>(this, R.layout.selectrow, diyListArray){
boolean[] checked = new boolean[diyListArray.size()];
#NonNull
#Override
public View getView(final int position, #Nullable View convertView, #NonNull ViewGroup parent) {
if(convertView == null) convertView = getLayoutInflater().inflate(R.layout.selectrow, null);
TextView textView = convertView.findViewById(R.id.test);
CheckBox checkBox = convertView.findViewById(R.id.checkBox1);
textView.setText(getItem(position));
checkBox.setChecked(checked[position]);
checkBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
checked[position] = !checked[position];
String msg = "Checked Item: ";
if(!checked[position]) msg = "Unchecked Item: ";
Toast.makeText(getContext(), msg + getItem(position), Toast.LENGTH_SHORT).show();
notifyDataSetChanged();
}
});
return convertView;
}
};
I have blog about ListView: http://programandroidlistview.blogspot.com/
Hope that helps!
Here, in a listview I have added a custom row in which Checkbox and EditText are there and with a add button I just add multiple views to my listview. Adding is working perfectly but when it comes to removing part the checked items are not removing and apart from that suppose I selected two items, then two items from last deleted. I don't know whats going on with my code please help me.
Here is my code:
MainActivity.java
public class MainActivity extends AppCompatActivity {
AdapterCustom customAdapter;
ArrayList<String> stringArrayList;
ListView listView;
ArrayList<Integer> listOfItemsToDelete;
AdapterCustom.ViewHolder item;
int POS;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listOfItemsToDelete = new ArrayList<Integer>();
stringArrayList = new ArrayList<String>();
LinearLayoutManager layoutManager
= new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
listView = (ListView) findViewById(R.id.list_item);
customAdapter = new AdapterCustom(MainActivity.this, R.layout.main, stringArrayList);
}
public void addItems(View v) {
stringArrayList.add("");
listView.setAdapter(customAdapter);
customAdapter.notifyDataSetChanged();
}
public void removeItems(View v) {
if (listOfItemsToDelete.isEmpty()) {
Toast.makeText(getBaseContext(), "No items selected.",
Toast.LENGTH_SHORT).show();
} else {
Log.i("Delete Pos", POS + "");
if (!listOfItemsToDelete.equals("")) {
for (int j = 0; j < listOfItemsToDelete.size(); j++) {
stringArrayList.remove(listOfItemsToDelete.get(j) - j);
customAdapter.notifyDataSetChanged();
}
}
}
}
AdapterCustom.java
public class AdapterCustom extends ArrayAdapter<String> {
Context context;
ArrayList<String> stringArrayList;
ArrayList<Boolean> positionArray;
MainActivity activity;
public AdapterCustom(Context context, int resourceId, ArrayList<String> arrayList) {
super(context, resourceId, arrayList);
this.context = context;
this.stringArrayList = arrayList;
positionArray = new ArrayList<Boolean>(stringArrayList.size());
for (int i = 0; i < stringArrayList.size(); i++) {
positionArray.add(false);
}
activity = new MainActivity();
}
#Override
public int getCount() {
return stringArrayList.size();
}
#Override
public String getItem(int position) {
return stringArrayList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public class ViewHolder {
EditText ediText;
CheckBox checkBox;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if (convertView == null) {
item = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(R.layout.main, null);
item.ediText = (EditText) convertView.findViewById(R.id.ediText);
item.checkBox = (CheckBox) convertView.findViewById(R.id.checkBox);
item.checkBox.setTag(new Integer(position));
convertView.setTag(item);
final View finalConvertView1 = convertView;
item.checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (b) {
int getPosition = (Integer) compoundButton.getTag();
POS = getPosition;
listOfItemsToDelete.add(POS);
Log.i("position after check", POS + "");
Log.i("position check array", listOfItemsToDelete + "");
}
}
});
} else {
item = (ViewHolder) convertView.getTag();
}
item.checkBox.setTag(position);
return convertView;
}
}
activity_main.xml
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:weightSum="10">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:orientation="horizontal"
android:weightSum="10">
<Button
android:id="#+id/addBtn"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="5"
android:onClick="addItems"
android:text="Add New Item" />
<Button
android:id="#+id/goBtn"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="5"
android:onClick="goItems"
android:text="Go to Item" />
</LinearLayout>
<ListView
android:id="#+id/list_item"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="8"
android:drawSelectorOnTop="false"
android:visibility="visible" />
<Button
android:id="#+id/removeBtn"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:onClick="removeItems"
android:text="Remove Item" />
</LinearLayout>
main.xml
<LinearLayout
android:id="#+id/custom"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="5dp"
android:weightSum="10">
<CheckBox
android:id="#+id/checkBox"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1" />
<EditText
android:id="#+id/ediText"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="9"
android:background="#android:color/white"
android:hint="Type Anything You Want" />
</LinearLayout>
You only remove the item from the array. Try removing the item also from the list view adapter with adapter.remove(itemPosition);
What does mean
- j
in this code:
for (int j = 0; j < listOfItemsToDelete.size(); j++) {
stringArrayList.remove(listOfItemsToDelete.get(j) - j);
customAdapter.notifyDataSetChanged();
}
?
I think that:
for (String itemToRemove:listOfItemsToDelete) {
stringArrayList.remove(itemToRemove);
}
customAdapter.notifyDataSetChanged();
listOfItemsToDelete.clear();
would be appropriate.
how do i add checkbox in my code? so user select multiple pictures using checkbox in gridview what do i do? I just want to add a checkbox in my gridview what do i do?
GridView gridView;
TextView textView;
File currentParent;
File[] currentFiles;
SimpleAdapter simpleAdapter;
File root1;
File root;
root1 = new File("/data/data/com.myexample.lock/files/");
currentParent = root1;
currentFiles = root1.listFiles();
currentFilePath = new String[currentFiles.length];
int count = 0;
for (File f : currentFiles) {
currentFilePath[count] = f.getAbsolutePath();
count++;
}
gridView = (GridView) findViewById(R.id.grid);
gridView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent,
View view, int position, long id) {
if (currentFiles[position].isDirectory()) {
root = new File("/data/data/com.myexample.lock/files/" +
FileName(currentFilePath[position]) + "/");
currentFiles = root.listFiles();
inflateListView(currentFiles);
} else if (currentFiles[position].isFile()) {
openFile(currentFiles[position]);
}
}
});
private void inflateListView(File[] files) {
List<Map<String, Object>> listItems = new ArrayList<Map<String, Object>>();
for (int i = 0; i < files.length; i++) {
Map<String, Object> listItem = new HashMap<String, Object>();
if (files[i].isDirectory()) {
listItem.put("icon", R.drawable.folder);
listItem.put("fileName", files[i].getName()+
"("+files[i].list().length+")");
} else {
listItem.put("icon", files[i]);
}
listItems.add(listItem);
}
simpleAdapter = new SimpleAdapter(this,
listItems, R.layout.line,new String[] {
"icon", "fileName" }, new int[] { R.id.icon, R.id.file_name });
}
line.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ffffff"
android:orientation="horizontal"
android:padding="5dip" >
<ImageView
android:id="#+id/icon"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/file_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/icon"
android:paddingLeft="5dp"
android:textColor="#000000"
android:textSize="12dp" />
</RelativeLayout>
Use custom adapter for your gridView. In the getView method you can inflate any layout you want for the cell
This the example of how i made a custom listview with Imageview and TextView. I did this because i also wanted to delete multiple items selected in the listview.
This is my java code:
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", "cat_id=?",
// new String[] { i + "" });
// ---------delete from category_fields
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);
}
}
This is my main layout code:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ffffff"
tools:context=".DeleteData" >
<RelativeLayout
android:id="#+id/relativeLayoutDeleteDataTopBar"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" >
<TextView
android:id="#+id/textViewDeleteDataScreenTitle"
style="#style/screen_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Delete Data" />
<ImageView
android:id="#+id/imageViewDeleteDataDelete"
android:layout_width="22dp"
android:layout_height="22dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="10dp"
android:src="#drawable/set_delete" />
</RelativeLayout>
<View
android:id="#+id/viewDeleteData"
android:layout_width="match_parent"
android:layout_height="5dp"
android:layout_below="#+id/relativeLayoutDeleteDataTopBar"
android:background="#drawable/shadow" />
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
android:id="#+id/linearLayoutDeleteDataAdMobBanner"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:orientation="vertical" >
<com.google.ads.AdView
android:id="#+id/adViewDeleteData"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
ads:adSize="BANNER"
ads:adUnitId="a1512f50d8c3692"
ads:loadAdOnCreate="true"
ads:testDevices="TEST_EMULATOR, TEST_DEVICE_ID" />
</LinearLayout>
<ListView
android:id="#+id/listViewDeleteData"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="#BDBDBD"
android:dividerHeight="1dp"
android:layout_below="#+id/viewDeleteData"
android:layout_above="#+id/linearLayoutDeleteDataAdMobBanner" >
</ListView>
</RelativeLayout>
And this is my custom layout code which i use to inflate in listview:
<?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="wrap_content"
android:background="#ffffff"
android:padding="15dp" >
<TextView
android:id="#+id/textViewSingleRowDeleteData"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
style="#style/listview_only_textview"
android:text="Category" />
<ImageView
android:id="#+id/imageViewSingleRowDeleteData"
android:layout_width="22dp"
android:layout_height="22dp"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:src="#drawable/set_basecircle" />
</RelativeLayout>
I have a problem syncing the list items isChecked state with the checkboxes that in the same raw. I am able to set the 'checked' state in list items but can't figure how to set the 'checked' state of the CheckBoxes. I thought mainListView.setItemChecked should do the work but it doesn't.
This is the code i'm using:
public class Reservation_Activity extends ListActivity {
int total=0;
private name_price[] lv_arr = {};
private ListView mainListView = null;
final String SETTING_TODOLIST = "todolist";
TextView total_tv;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.reservation);
total_tv = (TextView) findViewById(R.id.total_sum);
Button btnSave = (Button) findViewById(R.id.btnSave);
btnSave.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),
" You clicked Save button", Toast.LENGTH_SHORT).show();
}
});
Button btnClear = (Button) findViewById(R.id.btnClear);
btnClear.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
total=0;
total_tv.setText("Pick and Send");
Toast.makeText(getApplicationContext(),
" You clicked Clear button", Toast.LENGTH_SHORT).show();
ClearSelections();
}
});
// Prepare an ArrayList of todo items
ArrayList<name_price> listTODO = PrepareListFromXml();
this.mainListView = getListView();
mainListView.setCacheColorHint(0);
// Bind the data with the list
lv_arr = (name_price[]) listTODO.toArray(lv_arr);
mainListView.setAdapter(new MyAdapter(this,android.R.layout.simple_list_item_multiple_choice,lv_arr));
mainListView.setItemsCanFocus(false);
mainListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
mainListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,long arg3) {
name_price item = (name_price) mainListView.getItemAtPosition(position);
if(mainListView.isItemChecked(position))
{
mainListView.setItemChecked(position, false);
total = total - item._price;
} else {
mainListView.setItemChecked(position, true);
total += item._price;
}
total_tv.setText("Total: " + total);
}
});
}
private void ClearSelections() {
total=0;
// user has clicked clear button so uncheck all the items
int count = this.mainListView.getAdapter().getCount();
for (int i = 0; i < count; i++) {
this.mainListView.setItemChecked(i, false);
}
}
private ArrayList<name_price> PrepareListFromXml() {
ArrayList<name_price> todoItems = new ArrayList<name_price>();
XmlResourceParser todolistXml = getResources().getXml(R.xml.order_items);
int id=0;
int eventType = -1;
while (eventType != XmlResourceParser.END_DOCUMENT) {
if (eventType == XmlResourceParser.START_TAG) {
String strNode = todolistXml.getName();
if (strNode.equals("item")) {
todoItems.add(new name_price(id,todolistXml.getAttributeValue(null, "title"), Integer.parseInt(todolistXml.getAttributeValue(null, "price"))));
id++;
}
}
try {
eventType = todolistXml.next();
} catch (XmlPullParserException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return todoItems;
}
public class MyAdapter extends ArrayAdapter<name_price> {
name_price[] items;
public MyAdapter(Context context, int textViewResourceId,
name_price[] objects) {
super(context, textViewResourceId, objects);
this.items = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
View row = inflater.inflate(R.layout.list_raw_resevation, parent, false);
TextView name,price;
CheckBox ckbx = (CheckBox) row.findViewById(R.id.UpdateCheckBox);
ckbx.setChecked(mainListView.isItemChecked(position));
name = (TextView) row.findViewById(R.id.res_name);
name.setText(items[position]._name);
price = (TextView) row.findViewById(R.id.res_price);
price.setText(Integer.toString(items[position]._price));
return row;
}
public name_price getItem(int position) {
return items[position];
}
}
}
class name_price {
public String _name;
public int _price;
public int _id;
public CheckBox ckbx;
public name_price(int id, String name, int price)
{
this._id=id;
this._name = name;
this._price = price;
}
public name_price() {
// TODO Auto-generated constructor stub
}
}
I think I should change the checked state of the specific checkbox in mainListView.setOnItemClickListener according to this but I can't find a way to do it.
in addition, This is the raw layout and the list layout (of others to use):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:padding="6dip">
<LinearLayout
android:layout_width="0dip"
android:layout_height="fill_parent"
android:layout_weight="1"
android:orientation="horizontal" >
<TextView
android:id="#+id/res_name"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:layout_gravity="center_horizontal"
android:gravity="center|left"
android:singleLine="true"
android:text="lalalalalalalalalallaallllaaaa"
android:textColor="#ffffff" />
<TextView
android:id="#+id/res_price"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="center"
android:layout_marginRight="10dp"
android:gravity="center"
android:text="90"
android:textColor="#ffffff"
android:textSize="15dp" />
</LinearLayout>
<CheckBox android:text=""
android:id="#+id/UpdateCheckBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:focusable="false" />
</LinearLayout>
List layout:
<!--?xml version="1.0" encoding="utf-8"?-->
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:background="#81BEF7"
android:scrollbars="vertical">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/Buttonlayout" android:orientation="horizontal"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:height="32dp" android:gravity="left|top" android:background="#2B60DE"
android:paddingTop="2dp" android:paddingBottom="2dp">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/Buttonlayout2" android:orientation="horizontal"
android:layout_height="wrap_content" android:gravity="left|center_vertical"
android:layout_width="wrap_content" android:layout_gravity="left|center_vertical">
<TextView android:id="#+id/total_sum" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:textStyle="bold"
android:textColor="#FFFFFF" android:text="#string/list_header"
android:textSize="15sp" android:gravity="center_vertical"
android:paddingLeft="5dp">
</TextView>
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/Buttonlayout22" android:orientation="horizontal"
android:layout_height="wrap_content" android:gravity="right"
android:layout_width="fill_parent" android:layout_gravity="right|center_vertical">
<Button android:id="#+id/btnSave" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Send" android:textSize="15sp"
android:layout_marginLeft="10px" android:layout_marginRight="10px"
android:layout_marginBottom="2px" android:layout_marginTop="2px"
android:height="15dp" android:width="70dp">
</Button>
<Button android:id="#+id/btnClear" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="Clear" android:textSize="15sp"
android:layout_marginLeft="10px" android:layout_marginRight="10px"
android:layout_marginBottom="2px" android:layout_marginTop="2px"
android:height="15dp" android:width="70dp">
</Button>
</LinearLayout>
</LinearLayout>
<TableLayout android:id="#+id/TableLayout01" android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TableRow>
<ListView android:id="#android:id/list" android:layout_width="wrap_content"
android:textColor="#000000" android:layout_height="wrap_content">
</ListView>
</TableRow>
</TableLayout>
</LinearLayout>
Thanks!
Y
Good morning, I understand this should solve your problem:
public class Reservation_Activity extends ListActivity {
int total = 0;
private name_price[] lv_arr = {};
private ListView mainListView = null;
final String SETTING_TODOLIST = "todolist";
TextView total_tv;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list_raw_resevation);
total_tv = (TextView) findViewById(R.id.total_sum);
Button btnSave = (Button) findViewById(R.id.btnSave);
btnSave.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),
" You clicked Save button", Toast.LENGTH_SHORT).show();
}
});
Button btnClear = (Button) findViewById(R.id.btnClear);
btnClear.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
total = 0;
total_tv.setText("Pick and Send");
Toast.makeText(getApplicationContext(),
" You clicked Clear button", Toast.LENGTH_SHORT).show();
ClearSelections();
}
});
// Prepare an ArrayList of todo items
ArrayList<name_price> listTODO = PrepareListFromXml();
this.mainListView = getListView();
mainListView.setCacheColorHint(0);
// Bind the data with the list
lv_arr = (name_price[]) listTODO.toArray(lv_arr);
mainListView.setAdapter(new MyAdapter(this,
android.R.layout.simple_list_item_multiple_choice, lv_arr));
mainListView.setItemsCanFocus(false);
mainListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
mainListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
name_price item = (name_price) mainListView
.getItemAtPosition(position);
if (mainListView.isItemChecked(position)) {
total = total - item._price;
} else {
total += item._price;
}
mainListView.setItemChecked(position,
mainListView.isItemChecked(position));
item.ckbx.setChecked(mainListView.isItemChecked(position));
total_tv.setText("Total: " + total);
}
});
}
private void ClearSelections() {
total = 0;
int count = this.mainListView.getAdapter().getCount();
for (int i = 0; i < count; i++) {
this.mainListView.setItemChecked(i, false);
}
}
private ArrayList<name_price> PrepareListFromXml() {
ArrayList<name_price> todoItems = new ArrayList<name_price>();
XmlResourceParser todolistXml = getResources().getXml(R.xml.order_items);
int id = 0;
int eventType = -1;
while (eventType != XmlResourceParser.END_DOCUMENT) {
if (eventType == XmlResourceParser.START_TAG) {
String strNode = todolistXml.getName();
if (strNode.equals("item")) {
todoItems.add(new name_price(id, todolistXml.getAttributeValue(null, "title"),Integer.parseInt(todolistXml.getAttributeValue(null,"price"))));
id++;
}
}
try {
eventType = todolistXml.next();
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return todoItems;
}
public class MyAdapter extends ArrayAdapter<name_price> {
name_price[] items;
View row;
CheckBox ckbx;
public MyAdapter(Context context, int textViewResourceId,name_price[] objects) {
super(context, textViewResourceId, objects);
this.items = objects;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = getLayoutInflater();
row = inflater.inflate(R.layout.reservation, parent, false);
TextView name, price;
ckbx = (CheckBox) row.findViewById(R.id.UpdateCheckBox);
ckbx.setChecked(mainListView.isItemChecked(position));
ckbx.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
name_price item = (name_price) mainListView.getItemAtPosition(position);
if (ckbx.isChecked()) {
total = total - item._price;
} else {
total += item._price;
}
mainListView.setItemChecked(position,ckbx.isChecked());
total_tv.setText("Total: " + total);
}
});
items[position].setCkbx(ckbx);
name = (TextView) row.findViewById(R.id.res_name);
name.setText(items[position]._name);
price = (TextView) row.findViewById(R.id.res_price);
price.setText(Integer.toString(items[position]._price));
return row;
}
public name_price getItem(int position) {
return items[position];
}
}
}
and:
class name_price {
public String _name;
public int _price;
public int _id;
public CheckBox ckbx;
public name_price(int id, String name, int price) {
this._id = id;
this._name = name;
this._price = price;
}
public void setCkbx(CheckBox ckbx) {
this.ckbx = ckbx;
}
}