Android EditText in ListView Not able to edit - android

I am not able to edit the EditText. How it can be achieved ?
and also want to know how I can get the data from all Edittext. I am giving my classes and xml file here
MainActivity.java
package com.example.listviewdynamic;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
public class MainActivity extends Activity {
Button submit;
public static final String[] commodity = new String[] { "1", "2",
"3", "4" };
public static final String[] quantity = new String[] { "50", "40", "30",
"15", };
public static final String[] rate = new String[] { "2", "5", "3", "121", };
public static final String[] issue_qty = new String[] { "0.0", "0.0",
"0.0", "0.0", };
ListView listView;
List<RowItem> rowItems;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rowItems = new ArrayList<RowItem>();
for (int i = 0; i < commodity.length; i++) {
RowItem item = new RowItem(commodity[i], quantity[i], rate[i],
issue_qty[i]);
rowItems.add(item);
}
submit = (Button) findViewById(R.id.submit);
listView = (ListView) findViewById(R.id.list);
listView.setItemsCanFocus(true);
listView.setClickable(false);
CustomListAdapter adapter = new CustomListAdapter(this, rowItems);
listView.setAdapter(adapter);
// How to get the data ?
submit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Code To get data with id's from EditText
}
});
}
public void onItemSelected(AdapterView<?> listView, View view,
int position, long id) {
EditText yourEditText = (EditText) view.findViewById(R.id.issue_qty);
listView.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
yourEditText.requestFocus();
}
public void onNothingSelected(AdapterView<?> listView) {
listView.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);
}
}
CustomListAdapter.java
package com.example.listviewdynamic;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.TextView;
public class CustomListAdapter extends BaseAdapter {
Context context;
List<RowItem> rowItems;
public CustomListAdapter(Context context, List<RowItem> items) {
this.context = context;
this.rowItems = items;
}
private class ViewHolder {
TextView item;
TextView quantity;
TextView rate;
EditText issue_quantity;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_items, null);
holder = new ViewHolder();
holder.quantity = (TextView) convertView
.findViewById(R.id.quantity);
holder.item = (TextView) convertView.findViewById(R.id.item);
holder.rate = (TextView) convertView.findViewById(R.id.rate);
holder.issue_quantity = (EditText) convertView
.findViewById(R.id.issue_qty);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
RowItem rowItem = (RowItem) getItem(position);
holder.quantity.setText(rowItem.getQuantity());
holder.item.setText(rowItem.getItem());
holder.rate.setText(rowItem.getRate());
// holder.issue_quantity.setText(rowItem.getIssue_quantity());
return convertView;
}
#Override
public int getCount() {
return rowItems.size();
}
#Override
public Object getItem(int position) {
return rowItems.get(position);
}
#Override
public long getItemId(int position) {
return rowItems.indexOf(getItem(position));
}
}
RowItem.java
package com.example.listviewdynamic;
public class RowItem {
private String rate;
private String quantity;
private String item;
private String issue_quantity;
public RowItem(String item, String quantity, String rate, String issueQTY) {
this.issue_quantity = issueQTY;
this.item = item;
this.quantity = quantity;
this.rate = rate;
}
public String getRate() {
return rate;
}
public void setRate(String rate) {
this.rate = rate;
}
public String getQuantity() {
return quantity;
}
public void setQuantity(String quantity) {
this.quantity = quantity;
}
public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}
public String getIssue_quantity() {
return issue_quantity;
}
public void setIssue_quantity(String issue_quantity) {
this.issue_quantity = issue_quantity;
}
}
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="#+id/submit"
android:layout_width="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_height="wrap_content"
android:text="Submit" >
</Button>
</LinearLayout>
list_items.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:id="#+id/item"
android:layout_width="80dp"
android:layout_height="50dp"
android:paddingLeft="10dp"
android:paddingRight="10dp" />
<TextView
android:id="#+id/quantity"
android:layout_width="80dp"
android:layout_height="50dp"
android:paddingLeft="10dp"
android:paddingRight="10dp" />
<TextView
android:id="#+id/rate"
android:layout_width="80dp"
android:layout_height="50dp"
android:paddingLeft="10dp"
android:paddingRight="10dp" />
<EditText
android:id="#+id/issue_qty"
android:layout_width="80dp"
android:layout_height="50dp"
android:paddingLeft="10dp"
android:editable="true"
android:paddingRight="10dp" />
</LinearLayout>

EditTexts are not designed to be used inside ListViews. Alternatively you could use a ScrollView and populate the EditTexts dynamically.

Related

ListView not getting populated from the Adapter

This app is used to fetch the books as JSON using Google Books API and on research I also found that the JSON data is loading fine and the Book Title, Author is parsed correctly and I tested that using toasts. But the listView is not showing up even from setting the listView with the adapter. What must be the error? The app also doesn't crash making it little difficult to troubleshoot. Thanks in advance!
Main Activity
package com.praveent.booklisting;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Scanner;
public class MainActivity extends AppCompatActivity {
public String rootUrl = "https://www.googleapis.com/books/v1/volumes";
public String queryParameter = "q";
Button search_button;
EditText search_string;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.list_view);
search_button = (Button) findViewById(R.id.search_button);
search_string = (EditText) findViewById(R.id.search_string);
search_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String query = search_string.getText().toString();
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
if(activeNetworkInfo != null && activeNetworkInfo.isConnected()){
new BackgroundTask().execute(query);
}
else{
Toast.makeText(MainActivity.this, "Please switch on the internet!", Toast.LENGTH_SHORT).show();
}
}
});
}
public void populate(BookAdapter adapter){
listView.setAdapter(adapter);
}
public class BackgroundTask extends AsyncTask<String, JSONArray, String> {
#Override
protected String doInBackground(String... strings) {
String query = strings[0];
URL url = null;
Uri uri = Uri.parse(rootUrl).buildUpon().appendQueryParameter(queryParameter, query).build();
try {
url = new URL(uri.toString());
} catch (MalformedURLException e) {
e.printStackTrace();
}
String data = null;
try {
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
Scanner scanner = new Scanner(in);
scanner.useDelimiter("\\A");
if(scanner.hasNext()){
data = scanner.next();
}
} catch (IOException e1) {
e1.printStackTrace();
}
return data;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
BookAdapter bookAdapter;
JSONObject jsonObject = null;
JSONArray jsonArray = null;
JSONObject jsonArrayObject = null;
JSONObject volumeInfo = null;
JSONArray authorInfo = null;
JSONObject imageInfo = null;
String imageUrl = null;
String bookTitle = null;
String bookAuthor = null;
try {
jsonObject = new JSONObject(s);
jsonArray = jsonObject.getJSONArray("items");
ArrayList<Book> books= new ArrayList<Book>();
for(int i = 0; i <= jsonArray.length(); i++){
jsonArrayObject = jsonArray.getJSONObject(i);
volumeInfo = jsonArrayObject.getJSONObject("volumeInfo");
bookTitle = volumeInfo.getString("title");
authorInfo = volumeInfo.getJSONArray("authors");
bookAuthor = " ";
if (authorInfo != null){
bookAuthor = authorInfo.getString(0);
}
//imageInfo = volumeInfo.getJSONObject("imageLinks");
//imageUrl = imageInfo.getString("smallThumbnail");
books.add(new Book(bookTitle, bookAuthor));
Toast.makeText(MainActivity.this, bookAuthor, Toast.LENGTH_SHORT).show();
}
bookAdapter = new BookAdapter(MainActivity.this, books);
populate(bookAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
Book Adapter
package com.praveent.booklisting;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
public class BookAdapter extends ArrayAdapter<Book>{
Context c = null;
public BookAdapter(Context context, ArrayList<Book> books) {
super(context, 0, books);
c = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View listItemView = convertView;
if (listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.list_item, parent, false);
}
Book currentBook = getItem(position);
TextView bookTextView = (TextView) listItemView.findViewById(R.id.book_name);
bookTextView.setText(currentBook.getBookName());
TextView authorTextView = (TextView) listItemView.findViewById(R.id.book_author);
authorTextView.setText(currentBook.getAuthorName());
//ImageView coverImageView = (ImageView) listItemView.findViewById(R.id.cover_image);
//Picasso.with(c).load(currentBook.getImageURL()).into(coverImageView);
return listItemView;
}
}
Book Class
package com.praveent.booklisting;
public class Book {
private String bookName;
private String authorName;
private String imageURL;
public Book(String name, String author){
bookName = name;
authorName = author;
//imageURL = url;
}
public String getBookName() {
return bookName;
}
public String getAuthorName() {
return authorName;
}
public String getImageURL() {
return imageURL;
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="match_parent"
tools:context="com.praveent.booklisting.MainActivity">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="16dp"
android:id="#+id/search_string"
android:textAlignment="center"
android:gravity="center"
android:hint="#string/search_hint"/>
<Button
android:layout_width="match_parent"
android:id="#+id/search_button"
android:layout_height="wrap_content"
android:text="#string/search_button" />
<ListView
android:layout_width="fill_parent"
android:id="#+id/list_view"
android:layout_height="fill_parent">
</ListView>
</LinearLayout>
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal" android:layout_width="match_parent"
android:padding="8dp"
android:layout_height="wrap_content">
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:id="#+id/cover_image"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:layout_gravity="center"
android:orientation="vertical">
<TextView
android:id="#+id/book_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textColor="#000"
android:textSize="18sp"
android:textStyle="bold" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="16sp"
android:textColor="#000"
android:id="#+id/book_author"/>
</LinearLayout>
</LinearLayout>
On PostExecute Change
for(int i = 0; i <=jsonArray.length(); i++)
to for(int i = 0;i<jsonArray.length(); i++)
On list_item.xml change the text color to white
you need to call getCount() in adapter.
public class BookAdapter extends ArrayAdapter<Book>{
Context c = null;
ArrayList<Book> bookslist = new ArrayList();
public BookAdapter(Context context, ArrayList<Book> books) {
super(context, 0, books);
c = context;
bookslist = books;
}
#Override
public int getCount() {
return bookslist.size();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View listItemView = convertView;
if (listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.list_item, parent, false);
}
Book currentBook = getItem(position);
TextView bookTextView = (TextView) listItemView.findViewById(R.id.book_name);
bookTextView.setText(currentBook.getBookName());
TextView authorTextView = (TextView) listItemView.findViewById(R.id.book_author);
authorTextView.setText(currentBook.getAuthorName());
//ImageView coverImageView = (ImageView) listItemView.findViewById(R.id.cover_image);
//Picasso.with(c).load(currentBook.getImageURL()).into(coverImageView);
return listItemView;
}
}
Change your adapter to this
public class BookAdapter extends ArrayAdapter<Book> {
Context c = null;
private List<Book> bookList;
public BookAdapter(Context context, ArrayList<Book> books) {
super(context, 0, books);
c = context;
bookList = new ArrayList<>();
bookList = books;
}
#Override
public int getCount() {
return bookList.size();
}
#Nullable
#Override
public Book getItem(int position) {
return bookList.get(position);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View listItemView = convertView;
if (listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.list_item, parent, false);
}
Book currentBook = getItem(position);
TextView bookTextView = (TextView) listItemView.findViewById(R.id.book_name);
bookTextView.setText(currentBook.getBookName());
TextView authorTextView = (TextView) listItemView.findViewById(R.id.book_author);
authorTextView.setText(currentBook.getAuthorName());
//ImageView coverImageView = (ImageView) listItemView.findViewById(R.id.cover_image);
//Picasso.with(c).load(currentBook.getImageURL()).into(coverImageView);
return listItemView;
}
}
I checked your code Error is in the AsyncTask onPostExecute method, change your for loop condition to this
for(int i = 0; i < jsonArray.length(); i++)
It is now working.

Find the selected check boxes in a list view Android

I am working on a project and in that I want to get the track of items that are selected (check box) from a list view.
Is there any way of doing it?
Code so far is below;
Main Activity
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
public class MainActivity extends Activity {
ListView lv;
Model[] modelItems;
CheckBox ONE,TWO,THREE;
Button MultiData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.listView1);
modelItems = new Model[5];
modelItems[0] = new Model("pizza", 0);
modelItems[1] = new Model("burger", 0);
modelItems[2] = new Model("olives", 0);
modelItems[3] = new Model("orange", 0);
modelItems[4] = new Model("tomato", 0);
CustomAdapter adapter = new CustomAdapter(this, modelItems);
lv.setAdapter(adapter);
}
}
CustomAdapter
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.TextView;
import java.util.ArrayList;
public class CustomAdapter extends ArrayAdapter {
Model[] modelItems = null;
Context context;
public CustomAdapter(Context context, Model[] resource) {
super(context, R.layout.row1, resource);
this.context = context;
this.modelItems = resource;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
convertView = inflater.inflate(R.layout.row1, parent, false);
TextView name = (TextView) convertView.findViewById(R.id.textView1);
CheckBox cb = (CheckBox) convertView.findViewById(R.id.checkBox1);
name.setText(modelItems[position].getName());
if (modelItems[position].getValue() == 1)
cb.setChecked(true);
else
cb.setChecked(false);
return convertView;
}
}
Model
public class Model{
String name;
int value; /* 0 -> checkbox disable, 1 -> checkbox enable */
Model(String name, int value){
this.name = name;
this.value = value;
}
public String getName(){
return this.name;
}
public int getValue(){
return this.value;
}
}
main_xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
row1.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="horizontal" >
<CheckBox
android:id="#+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
</LinearLayout>
Eidt1 in Main Activity
boolean modelItemBool[] = new boolean[modelItems.length];
for (int h =0;h<modelItemBool.length;h++){
modelItemBool[h] = false;
}
Eidt 2
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
convertView = inflater.inflate(R.layout.row1, parent, false);
TextView name = (TextView) convertView.findViewById(R.id.textView1);
CheckBox cb = (CheckBox) convertView.findViewById(R.id.checkBox1);
name.setText(modelItems[position].getName());
cb.setOnCheckedChangeListener(new
CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
modelItems[position].getValue() == 1;
}else{
modelItems[position].getValue() == 0;
}
}
});
return convertView;
}
try this
create Boolean array same as your modelItems size and store true false value in that array
Step 1 : by default store all value false in array
Step 2 : update value in array on checkbox check state change
Add the code below before return convertView; then modelItems array will be updated every time a checkbox is checked/unchecked
final int posFinal = position;
cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
modelItems[posFinal].setValue( b ? 1 : 0);
}
});
new a list to keep selected items:
List<Model> selectedList = new ArrayList<>();
private List getSelectedList(){
if(!selectedList.isEmpty()) selectedList.clear();
for (int i=0;i<array.length;i++){
if(modelItems [i].getValue==1){
selectedList.add(modelItems [i]);
}
}
return selectedList;
}
set onCheckedChangeListener for CheckBox in getView:
cb.setOnCheckedChangeListener(new
CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
modelItems[position].setValue(1);
}else{
modelItems[position].setValue(0);
}
}
});
// Replace your code with bellow, on the click of button it will show selected checkbox name in alert dialog.
// MainActivity
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
public class MainActivity extends Activity {
ListView lv;
Model[] modelItems;
Button btn;
String selectedCheckBoxNAme = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_xml);
lv = (ListView) findViewById(R.id.listView1);
btn = (Button)findViewById(R.id.btn) ;
modelItems = new Model[5];
modelItems[0] = new Model("pizza", 0);
modelItems[1] = new Model("burger", 0);
modelItems[2] = new Model("olives", 0);
modelItems[3] = new Model("orange", 0);
modelItems[4] = new Model("tomato", 0);
CustomAdapter adapter = new CustomAdapter(this, modelItems);
lv.setAdapter(adapter);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
selectedCheckBoxNAme = "";
for (int i = 0; i < modelItems.length; i++) {
Model obj= modelItems [i];
if(obj.getValue() == 1)
{
selectedCheckBoxNAme = selectedCheckBoxNAme +"\n" + obj.getName();
}
}
if(!selectedCheckBoxNAme.isEmpty()) {
new AlertDialog.Builder(MainActivity4.this).setTitle("").setMessage(selectedCheckBoxNAme)
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
}
})
.setCancelable(false).create().show();
}
}
});
}
}
// CustomAdapter.java
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.TextView;
public class CustomAdapter extends ArrayAdapter {
Model[] modelItems = null;
Context context;
public CustomAdapter(Context context, Model[] resource) {
super(context, R.layout.row1, resource);
this.context = context;
this.modelItems = resource;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
convertView = inflater.inflate(R.layout.row1, parent, false);
TextView name = (TextView) convertView.findViewById(R.id.textView1);
CheckBox cb = (CheckBox) convertView.findViewById(R.id.checkBox1);
name.setText(modelItems[position].getName());
if (modelItems[position].getValue() == 1)
cb.setChecked(true);
else
cb.setChecked(false);
cb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
modelItems[position].setValue(1);
}else{
modelItems[position].setValue(0);
}
}
});
return convertView;
}
}
//main_xml.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"
>
<ListView
android:id="#+id/listView1"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_above="#+id/btn">
</ListView>
<Button
android:id="#+id/btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Here"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"/>
</RelativeLayout>
// Model
public class Model {
String name;
int value; /* 0 -> checkbox disable, 1 -> checkbox enable */
Model(String name, int value){
this.name = name;
this.value = value;
}
public String getName(){
return this.name;
}
public int getValue(){
return this.value;
}
public void setValue(int value)
{
this.value = value;
}
}

How to make a ListView with 4 sub items onClick Item detail View

How I can create a list view with 4 subitems which can contain Name, Phone,Mobile,Email
I am very new android learner
Ex:
Name 1
Ph:123456
Mo:123456789
email:example#example.com
--------------------------
Name 2
Ph:123456
Mo:123456789
email:example#example.com
--------------------------
Name 3
Ph:123456
Mo:123456789
email:example#example.com
--------------------------
Here is My Code which show one line as each list Item GMOFragment.java
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import com.rupomkhondaker.sonalibank.adapter.PhoneListAdapter;
import com.rupomkhondaker.sonalibank.model.ContactItem;
import java.io.Serializable;
import java.util.ArrayList;
public class GMOFragment extends android.app.Fragment {
public GMOFragment(){}
private ArrayList<ContactItem> phoneItems;
private PhoneListAdapter adapters;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_gmo, container, false);
ArrayList<ContactItem> listData = getListData();
final ListView listView = (ListView) rootView.findViewById(R.id.gmolistView);
listView.setAdapter(new PhoneListAdapter(getActivity(), listData));
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
ContactItem newsData = (ContactItem) listView.getItemAtPosition(position);
Toast.makeText(getActivity(), "Selected :" + " " + newsData, Toast.LENGTH_LONG).show();
Intent in = new Intent(getActivity(), ContactDetail.class);
// sending data to new activity
//!!! I NEED HELP HERE !!!!
//
startActivity(in);
}
});
return rootView;
}
private ArrayList<ContactItem> getListData() {
ArrayList<ContactItem> listMockData = new ArrayList<ContactItem>();
String[] names = getResources().getStringArray(R.array.gmo_name_list);
String[] phones = getResources().getStringArray(R.array.gmo_ph_list);
String[] mobiles = getResources().getStringArray(R.array.gmo_mob_list);
String[] emails = getResources().getStringArray(R.array.gmo_email_list);
for (int i = 0; i < names.length; i++) {
ContactItem newsData = new ContactItem();
newsData.setName(names[i]);
newsData.setPhone(phones[i]);
newsData.setMobile(mobiles[i]);
newsData.setEmail(emails[i]);
listMockData.add(newsData);
}
return listMockData;
}
}
also How to pass the Item and sub-item Data to next Activity ContactDetailActivity.class
Here is the code where I am trying to view data
import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.widget.TextView;
public class ContactDetailActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.fragment_service_details);
TextView txtName = (TextView) findViewById(R.id.conName);
TextView txtPhone = (TextView) findViewById(R.id.conPhone);
TextView txtMobile = (TextView) findViewById(R.id.conMobile);
TextView txtEmail = (TextView) findViewById(R.id.conEmail);
Intent i = getIntent();
// getting attached intent data
String name = i.getStringExtra("KEY_DATA");
String phone = i.getStringExtra("KEY_DATA2");
String mobile = i.getStringExtra("KEY_DATA3");
String email = i.getStringExtra("KEY_DATA4");
// displaying selected contact name
txtName.setText(name);
txtPhone.setText(phone);
txtMobile.setText(mobile);
txtEmail.setText(email);
}
}
You need to create your own custom adapter and custom view.
Check out the following tutorials -
Tutorial 1
Tutorial 2
Let me know If you having trouble understanding the concept.
Here is a working code -
Custom Adapter -
public class CustomAdapter extends ArrayAdapter<CustomObject> {
public CustomAdapter(Context context, List<CustomObject> objects) {
super(context, -1, objects);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
View view = convertView;
if (view == null) {
view = View.inflate(getContext(), R.layout.list_view_item, null);
viewHolder = new ViewHolder();
viewHolder.setView(view);
} else {
viewHolder = (ViewHolder) view.getTag();
}
viewHolder.mName.setText(getItem(position).getName());
viewHolder.mPhone.setText(getItem(position).getPhone());
viewHolder.mMobile.setText(getItem(position).getMobile());
viewHolder.mEmail.setText(getItem(position).getEmail());
return view;
}
private class ViewHolder {
public TextView mName;
public TextView mPhone;
public TextView mMobile;
public TextView mEmail;
public void setView(View view) {
mName = (TextView) view.findViewById(R.id.textView);
mPhone = (TextView) view.findViewById(R.id.textView2);
mMobile = (TextView) view.findViewById(R.id.textView3);
mEmail = (TextView) view.findViewById(R.id.textView4);
view.setTag(this);
}
}
}
Custom Object -
public class CustomObject implements Parcelable {
public String mName;
public String mPhone;
public String mMobile;
public String mEmail;
public CustomObject(String name, String phone, String mobile, String email) {
mName = name;
mPhone = phone;
mMobile = mobile;
mEmail = email;
}
private CustomObject(Parcel parcel) {
readFromParcel(parcel);
}
public String getName() {
return mName;
}
public void setName(String name) {
mName = name;
}
public String getPhone() {
return mPhone;
}
public void setPhone(String phone) {
mPhone = phone;
}
public String getMobile() {
return mMobile;
}
public void setMobile(String mobile) {
mMobile = mobile;
}
public String getEmail() {
return mEmail;
}
public void setEmail(String email) {
mEmail = email;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(mName);
dest.writeString(mPhone);
dest.writeString(mMobile);
dest.writeString(mEmail);
}
private void readFromParcel(Parcel parcel) {
mName = parcel.readString();
mPhone = parcel.readString();
mMobile = parcel.readString();
mEmail = parcel.readString();
}
public static final Creator<CustomObject> CREATOR = new Creator<CustomObject>() {
#Override
public CustomObject createFromParcel(Parcel source) {
return new CustomObject(source);
}
#Override
public CustomObject[] newArray(int size) {
return new CustomObject[0];
}
};
}
Your Activity -
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = (ListView) findViewById(R.id.listView);
ArrayList<CustomObject> customObjects = new ArrayList<>();
for (int i = 0; i < 5; i++) {
CustomObject customObject = new CustomObject("Name", "Phone", "Mobile", "Email");
customObjects.add(customObject);
}
CustomAdapter customAdapter = new CustomAdapter(this, customObjects);
listView.setAdapter(customAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
CustomObject object = customAdapter.getItem(position);
Intent intent = new Intent(this, NextActivity.class);
intent.putExtra("Item", customObjects);
startActivity(intent);
}
});
}
}
Custom View (list_view_item.xml) -
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/textView"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/textView2"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/textView3"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:id="#+id/textView4"/>
</LinearLayout>
activity_main.xml -
<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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".MainActivity">
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
If anything doesn't make sense, let me know, I'll explain it to you.

Dialog file to update list rows does not work / OnItemLongClick

I managed to get Dialog to show up on the long click by implementing this code:
ListView list = getListView();
list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
new EditListItemDialog(view.getContext()).show();
return true;
}
});
Unfortunately, when the dialog opens and prompts for new text input, when clicked ok, no changes are made to the list.
Here is the Dialog file:
package com.example.classorganizer;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
class EditListItemDialog extends Dialog implements View.OnClickListener {
private View editText;
public EditListItemDialog(Context context) {
super(context);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_text_dialog);//here is your xml with EditText and 'Ok' and 'Cancel' buttons
View btnOk = findViewById(R.id.button_ok);
editText = findViewById(R.id.edit_text);
btnOk.setOnClickListener(this);
}
#Override
public void onClick(View v) {
((TextView) editText).getText().toString();//here is your updated(or not updated) text
dismiss();
}
}
Here is the file containing list:
package com.example.classorganizer;
import java.util.ArrayList;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.cookbook.data.Constants;
import com.cookbook.data.MyDB;
public class Monday extends ListActivity {
private static final int MyMenu = 0;
MyDB dba;
DiaryAdapter myAdapter;
private class MyDiary{
public MyDiary(String t, String c){
title=t;
content=c;
ListView list = getListView();
list.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
new EditListItemDialog(view.getContext()).show();
return true;
}
});
}
public String title;
public String content;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
dba = new MyDB(this);
dba.open();
setContentView(R.layout.fragment_monday);
super.onCreate(savedInstanceState);
myAdapter = new DiaryAdapter(this);
this.setListAdapter(myAdapter);
}
private class DiaryAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private ArrayList<MyDiary> fragment_monday;
public DiaryAdapter(Context context) {
mInflater = LayoutInflater.from(context);
fragment_monday = new ArrayList<MyDiary>();
getdata();
}
public void getdata(){
Cursor c = dba.getdiaries();
startManagingCursor(c);
if(c.moveToFirst()){
do{
String title =
c.getString(c.getColumnIndex(Constants.TITLE_NAME));
String content =
c.getString(c.getColumnIndex(Constants.CONTENT_NAME));
MyDiary temp = new MyDiary(title,content);
fragment_monday.add(temp);
} while(c.moveToNext());
}
}
#Override
public int getCount() {return fragment_monday.size();}
public MyDiary getItem(int i) {return fragment_monday.get(i);}
public long getItemId(int i) {return i;}
public View getView(int arg0, View arg1, ViewGroup arg2) {
final ViewHolder holder;
View v = arg1;
if ((v == null) || (v.getTag() == null)) {
v = mInflater.inflate(R.layout.diaryrow, null);
holder = new ViewHolder();
holder.mTitle = (TextView)v.findViewById(R.id.name);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
holder.mdiary = getItem(arg0);
holder.mTitle.setText(holder.mdiary.title);
v.setTag(holder);
return v;
}
public class ViewHolder {
MyDiary mdiary;
TextView mTitle;
}
}
/** Called when the user clicks the Edit button */
public void visitDiary(View view) {
Intent intent = new Intent(this, Diary.class);
startActivity(intent);
}
/** Called when the user clicks the back button */
public void visitSchedule(View view) {
Intent intent = new Intent(this, DisplayScheduleScreen.class);
startActivity(intent);
}
}
Here is an xml file for dialog:
<?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" >
<RelativeLayout
android:id="#+id/relativeLayout4"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1" >
<EditText
android:id="#+id/edit_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10" >
<requestFocus />
</EditText>
<Button
android:id="#+id/button_ok"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="OK" />
</RelativeLayout>
</LinearLayout>
I don't understand why the rows are not being updated with data entered through Dialog file...
#Override
public void onClick(View v) {
((TextView) editText).getText().toString();//here is your updated(or not updated) text
dismiss();
}
You are getting the value from TextView of the dialog ,have u added the data to the list.
Update the data to the list
fragment_monday.add(((TextView) editText).getText().toString());

How to send selected messages using checkbox to a particular no?

first i'm fetching all messages to my app to be store in listview then I'm selecting messages from listview using checkboxes and wish to send these selected sms to a single number that is predefined and wish to use the selected sms as body of message to be send to single no. but the problem is that the message sent contains complete listview messages not the selected one. So please someone correct me where i'm wrong in code as i wish to send only selected messages not the complete listview items(messages)
public class MainActivity extends Activity implements OnItemClickListener, OnClickListener{
Button send;
ListView listViewSMS;
Cursor cursor;
SMSListAdapter smsListAdapter;
Context context;
SharedPreferences prefs=null;
ArrayAdapter<SMSListModel> adapter;
List<SMSListModel> list = new ArrayList<SMSListModel>();
TextView textViewSMSSender, textViewSMSBody;
int i;
int count = 0;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context=this;
listViewSMS=(ListView)findViewById(R.id.lvSMS);
send = (Button)findViewById(R.id.btnproperty);
send.setOnClickListener(this);
textViewSMSSender=(TextView)findViewById(R.id.tvSMSSend);
textViewSMSBody=(TextView)findViewById(R.id.tvSMSBody);
cursor = getContentResolver().query(Uri.parse("content://sms/inbox"), null, null, null, null);
smsListAdapter = new SMSListAdapter(this,getModel());
listViewSMS.setAdapter(smsListAdapter);
listViewSMS.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> arg0, View v, int arg2, long arg3) {
TextView label = (TextView) v.getTag(R.id.tvSMSSend);
CheckBox checkbox = (CheckBox) v.getTag(R.id.cbSelect);
Toast.makeText(v.getContext(), label.getText().toString()+" "+isCheckedOrNot(checkbox), Toast.LENGTH_LONG).show();
}
private String isCheckedOrNot(CheckBox checkbox) {
if(checkbox.isChecked())
return "is checked";
else
return "is not checked";
}
private List<SMSListModel> getModel() {
if(cursor.getCount()>0){
for(i=0;i<cursor.getCount();i++){
if(cursor.moveToPosition(i)){
list.add(new SMSListModel(cursor.getString(cursor.getColumnIndex("address")),cursor.getString(cursor.getColumnIndex("body"))));
}
}
}
return list;
}
#Override
public void onClick(View v) {
if( v == send){
mDialog();
}
public void mDialog(){
// Show The Dialog with Selected SMS
AlertDialog dialog = new AlertDialog.Builder(context).create();
dialog.setTitle("Message App");
dialog.setIcon(android.R.drawable.ic_dialog_info);
dialog.setMessage("Count : ");
dialog.setButton(DialogInterface.BUTTON_POSITIVE, "ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which)
{
String phoneNo = "111";
if(list.size()>0){
for(i=0;i<list.size();i++){
if(list.get(i).isSelected()){
try{
SmsManager smsManager = SmsManager.getDefault();
StringBuilder builder = new StringBuilder();
for(SMSListModel p: list){
builder.append(p.toString());
builder.append('\n');
}
String sms = builder.toString();
smsManager.sendTextMessage(phoneNo, null, sms, null, null);
Toast.makeText(getApplicationContext(), "SMS Sent!",Toast.LENGTH_LONG).show();
}
catch (Exception e){
Toast.makeText(getApplicationContext(),"SMS faild, please try again later!",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
dialog.dismiss();
}
}
}
}
});
dialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), "SMS not Sent",Toast.LENGTH_LONG).show();
dialog.dismiss();
}
});
dialog.show();
}
public class SMSListAdapter extends ArrayAdapter<SMSListModel> {
private final List<SMSListModel> list;
private final Activity mContext;
boolean checkAll_flag = false;
boolean checkItem_flag = false;
public SMSListAdapter(Activity context,List<SMSListModel> list)
{
super(context, R.layout.listview_each_item, list);
mContext = context;
this.list = list;
}
static class ViewHolder {
protected TextView textAddress;
protected TextView textBody;
protected CheckBox checkbox;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
if (convertView == null) {
LayoutInflater inflator = mContext.getLayoutInflater();
convertView = inflator.inflate(R.layout.listview_each_item, null);
viewHolder = new ViewHolder();
viewHolder.textAddress = (TextView) convertView.findViewById(R.id.tvSMSSend);
viewHolder.textBody = (TextView) convertView.findViewById(R.id.tvSMSBody);
viewHolder.checkbox = (CheckBox) convertView.findViewById(R.id.cbSelect);
viewHolder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int getPosition = (Integer) buttonView.getTag(); // Here we get the position that we have set for the checkbox using setTag.
list.get(getPosition).setSelected(buttonView.isChecked()); // Set the value of checkbox to maintain its state.
}
});
convertView.setTag(viewHolder);
convertView.setTag(R.id.tvSMSSend, viewHolder.textAddress);
convertView.setTag(R.id.tvSMSBody, viewHolder.textBody);
convertView.setTag(R.id.cbSelect, viewHolder.checkbox);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.checkbox.setTag(position); // This line is important.
viewHolder.textAddress.setText(list.get(position).getAddress());
viewHolder.textBody.setText(list.get(position).getBody());
viewHolder.checkbox.setChecked(list.get(position).isSelected());
return convertView;
}
public class SMSListModel {
private String address;
String body;
private boolean selected;
public SMSListModel(String address, String body) {
this.address = address;
this.body = body;
}
public String getAddress() {
return address;
}
public String getBody() {
return body;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
public String toString(){
return body;
}}
May I know why you want to select multiple rows. I mean what exact action you want to perform by selecting multiple rows?
Here is the updated code for you. Please let me know in case you didn't get any code:
---------------
package com.example.multiselectlist;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnItemClickListener, OnClickListener{
Button btnDelete;
ListView listViewSMS;
Cursor cursor;
SMSListAdapter smsListAdapter;
Context context;
ArrayAdapter<SMSListModel> adapter;
List<SMSListModel> list = new ArrayList<SMSListModel>();
int count = 0;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
context=this;
listViewSMS=(ListView)findViewById(R.id.lvSMS);
btnDelete = (Button)findViewById(R.id.buttonDelete);
cursor = getContentResolver().query(Uri.parse("content://sms/inbox"), null, null, null, null);
smsListAdapter = new SMSListAdapter(this,getModel());
listViewSMS.setAdapter(smsListAdapter);
listViewSMS.setOnItemClickListener(this);
btnDelete.setOnClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> arg0, View v, int arg2, long arg3) {
TextView label = (TextView) v.getTag(R.id.tvSMSSend);
CheckBox checkbox = (CheckBox) v.getTag(R.id.cbSelect);
Toast.makeText(v.getContext(), label.getText().toString()+" "+isCheckedOrNot(checkbox), Toast.LENGTH_LONG).show();
}
private String isCheckedOrNot(CheckBox checkbox) {
if(checkbox.isChecked())
return "is checked";
else
return "is not checked";
}
private List<SMSListModel> getModel() {
if(cursor.getCount()>0){
for(int i=0;i<cursor.getCount();i++){
if(cursor.moveToPosition(i)){
list.add(new SMSListModel(cursor.getString(cursor.getColumnIndex("address")),cursor.getString(cursor.getColumnIndex("body"))));
}
}
}
return list;
}
#Override
public void onClick(View v) {
int id = v.getId();
switch(id){
case R.id.buttonDelete:
if(list.size()>0){
for(int i=0;i<list.size();i++){
if(list.get(i).isSelected()){
list.remove(i);
}
}
smsListAdapter = new SMSListAdapter(this,list);
smsListAdapter.notifyDataSetChanged();
listViewSMS.setAdapter(smsListAdapter);
}
break;
case R.id.buttonSend:
String contactNum = "+123456789";
String messageList = "";
if(list.size()>0){
for(int i=0;i<list.size();i++){
if(list.get(i).isSelected()){
if(messageList.equals(""))
messageList = list.get(i).getBody();
else
messageList = messageList+";"+list.get(i).getBody();
}
}
Log.v("messageList",""+messageList);
Uri sendSmsTo = Uri.parse("smsto:" + contactNum);
Log.d("sendSmsTo",""+sendSmsTo);
Intent intent = new Intent(android.content.Intent.ACTION_SENDTO, sendSmsTo);
intent.putExtra("sms_body", messageList);
startActivityForResult(intent, 100);
}
}
}
}
SMSListModel class:
package com.example.multiselectlist;
public class SMSListModel {
private String address;
String body;
private boolean selected;
public SMSListModel(String address, String body) {
this.address = address;
this.body = body;
}
public String getAddress() {
return address;
}
public String getBody() {
return body;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
}
SMSListAdapter class:
package com.example.multiselectlist;
import java.util.List;
import android.app.Activity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;
public class SMSListAdapter extends ArrayAdapter<SMSListModel> {
private final List<SMSListModel> list;
private final Activity mContext;
boolean checkAll_flag = false;
boolean checkItem_flag = false;
public SMSListAdapter(Activity context,List<SMSListModel> list)
{
super(context, R.layout.listview_each_item, list);
mContext = context;
this.list = list;
}
static class ViewHolder {
protected TextView textAddress;
protected TextView textBody;
protected CheckBox checkbox;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
if (convertView == null) {
LayoutInflater inflator = mContext.getLayoutInflater();
convertView = inflator.inflate(R.layout.listview_each_item, null);
viewHolder = new ViewHolder();
viewHolder.textAddress = (TextView) convertView.findViewById(R.id.tvSMSSend);
viewHolder.textBody = (TextView) convertView.findViewById(R.id.tvSMSBody);
viewHolder.checkbox = (CheckBox) convertView.findViewById(R.id.cbSelect);
viewHolder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int getPosition = (Integer) buttonView.getTag(); // Here we get the position that we have set for the checkbox using setTag.
list.get(getPosition).setSelected(buttonView.isChecked()); // Set the value of checkbox to maintain its state.
}
});
convertView.setTag(viewHolder);
convertView.setTag(R.id.tvSMSSend, viewHolder.textAddress);
convertView.setTag(R.id.tvSMSBody, viewHolder.textBody);
convertView.setTag(R.id.cbSelect, viewHolder.checkbox);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.checkbox.setTag(position); // This line is important.
viewHolder.textAddress.setText(list.get(position).getAddress());
viewHolder.textBody.setText(list.get(position).getBody());
viewHolder.checkbox.setChecked(list.get(position).isSelected());
return convertView;
}
}
xml:
<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:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<Button
android:id="#+id/buttonDelete"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="Delete" />
<ListView
android:id="#+id/lvSMS"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/buttonDelete" >
</ListView>
</RelativeLayout>
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<CheckBox
android:id="#+id/cbSelect"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true" />
<TextView
android:id="#+id/tvSMSSend"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/cbSelect"
android:layout_marginLeft="10dp"
android:layout_toRightOf="#+id/cbSelect"
android:text="9998698700" />
<TextView
android:id="#+id/tvSMSBody"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/tvSMSSend"
android:layout_marginLeft="10dp"
android:layout_toRightOf="#+id/tvSMSSend"
android:text="body" />
</RelativeLayout>
You can always use:
yourListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
To choose multiple items, remember that its interface depend on you creating it.
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_pressed="true"
android:drawable="#color/white" />
<item
android:state_selected="true"
android:drawable="#drawable/list_item_bg_selected" />
<item
android:drawable="#color/list_bg" />
</selector>

Categories

Resources