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

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>

Related

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;
}
}

My list view is not showing anything i have use array adapter and no error in logcat

I am not getting anything in the listview when i am running this code.
I am trying to get value from server in text view,i am getting value from server in payload object.but still my list view is not showing anything and there is no error in logcat.
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.zalonstyles.app.zalon.Model.Services;
import com.zalonstyles.app.zalon.Model.ViewHolder;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
This is the class where i am getting data from server
public class popup_massage extends AppCompatActivity {
public static final String URL = "http://52.41.72.46:8080/service/get_category";
public final String serviceid = "6";
private ListView mainListView;
private Button check;
private List<Services> massagelist = new ArrayList<>();
private Services massageservice[];
private Context context;
public ArrayAdapter<Services> listAdapter;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.popup_massage);
SharedPreferences mSharedPreference= PreferenceManager.getDefaultSharedPreferences(getBaseContext());
String value=(mSharedPreference.getString("AppConstant.AUTH_TOKEN", "DEFAULT"));
Log.e("accesslog",value);
mainListView = (ListView) findViewById(R.id.listView4);
check = (Button) findViewById(R.id.button4);
final JSONObject params = new JSONObject();
try {
params.put("service_id",serviceid);
} catch (JSONException e) {
e.printStackTrace();
}
try {
params.put("access_token", value);
} catch (JSONException e) {
e.printStackTrace();
}
StringRequest stringRequest = new StringRequest(Request.Method.POST, URL,
new Response.Listener<String>(){
#Override
public void onResponse(String response) {
Log.v("updateUPVolleyRes1",response);
try {
JSONObject jobject = new JSONObject(response);
JSONArray payload = jobject.getJSONArray("payload");
Log.e("payloaddata", String.valueOf(payload));
for (int i = 0; i < payload.length(); i++) {
try{
JSONObject obj = payload.getJSONObject(i);
Services service = new Services();
service.setName(obj.getString("name"));
service.setcategotry_id(obj.getString("id"));
massagelist.add(service);
}finally {
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.v("updateUPVolleyErr", error.toString());
}
}){
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params1 = new HashMap<String, String>();
params1.put("payload", params.toString());
Log.v("updateUPVolleyParams", params1.toString());
return params1;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
mainListView
.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View item,
int position, long id)
{
Services massageservice = listAdapter.getItem(position);
Log.e("CHECKADAPTOR", String.valueOf(massageservice));
massageservice.toggleChecked();
ViewHolder viewHolder =(ViewHolder) item
.getTag();
viewHolder.getCheckBox().setChecked(massageservice.isChecked());
}
});
//Services[] massageService = (Services[]) getLastNonConfigurationInstance();ArrayList<Services> massagelist = new ArrayList<Services>();
//massagelist.addAll(Arrays.asList(massageService));
// Set our custom array adapter as the ListView's adapter.
listAdapter = new massageArrayAdapter(this,massagelist);
mainListView.setAdapter(listAdapter);
check.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
for (int i = 0; i < listAdapter.getCount(); i++)
{
Services massage = listAdapter.getItem(i);
if (massage.isChecked())
{
Toast.makeText(getApplicationContext(),
massage.getName() + " is Checked!!",
Toast.LENGTH_SHORT).show();
Log.v("My Custom Tag", massage.getName());
}
}
}
});
}
//arrayadapter class//
private static class massageArrayAdapter extends ArrayAdapter<Services>
{
private LayoutInflater inflater;
public massageArrayAdapter(Context context, List<Services> massagelist)
{
super(context, R.layout.customlist_massage, R.id.massagetextview, massagelist);
// Cache the LayoutInflate to avoid asking for a new one each time.
inflater = LayoutInflater.from((Context) context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
// services to display
Services massage = (Services) this.getItem(position);
// The child views in each row.
CheckBox checkBox;
TextView textView;
// Create a new row view
if (convertView == null)
{
convertView = inflater.inflate(R.layout.customlist_massage,null );
// Find the child views.
textView = (TextView) convertView
.findViewById(R.id.massagetextview);
checkBox = (CheckBox) `enter code here`convertView.findViewById(R.id.checkBox4);
// Optimization: Tag the row with it's child views, so we don't
// have to
// call findViewById() later when we reuse the row.
convertView.setTag(new ViewHolder(textView, checkBox));
// If CheckBox is toggled, update the planet it is tagged with.
checkBox.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
CheckBox cb = (CheckBox) v;
Services massage = (Services) cb.getTag();
massage.setChecked(cb.isChecked());
}
});
}
// Reuse existing row view
else
{
// Because we use a ViewHolder, we avoid having to call
// findViewById().
ViewHolder viewHolder = (ViewHolder) convertView
.getTag();
checkBox = viewHolder.getCheckBox();
textView = viewHolder.getTextView();
}
// Tag the CheckBox with the service it is displaying,
// access the planet in onClick() when the CheckBox is toggled.
checkBox.setTag(massage);
// Display planet data
checkBox.setChecked(massage.isChecked());
textView.setText(massage.getName());
return convertView;
}
}
}
My Service class used to store services
public class Services
{
private String name = "";
private boolean checked = false;
private String categotry_id="";
public Services()
{
}
public Services(String name)
{
this.name = name;
}
public Services(String name, boolean checked,String categotry_id)
{
this.name = name;
this.categotry_id = categotry_id;
this.checked = checked;
}
public Services(String name,String categotry_id)
{
this.name = name;
this.categotry_id = categotry_id;
}
public String getCategory_id(String id)
{
return categotry_id;
}
public void setcategotry_id(String categotry_id)
{
this.name = categotry_id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public boolean isChecked()
{
return checked;
}
public void setChecked(boolean checked)
{
this.checked = checked;
}
public String toString()
{
return name;
}
public void toggleChecked()
{
checked = !checked;
}
}
View holder class for storing views
public class ViewHolder
{
private CheckBox checkBox;
private TextView textView;
public ViewHolder()
{
}
public ViewHolder(TextView textView, CheckBox checkBox)
{
this.checkBox = checkBox;
this.textView = textView;
}
public CheckBox getCheckBox()
{
return checkBox;
}
public void setCheckBox(CheckBox checkBox)
{
this.checkBox = checkBox;
}
public TextView getTextView()
{
return textView;
}
public void setTextView(TextView textView)
{
this.textView = textView;
}
}
my xml class where list view is there
<?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"
android:background="#3F51B5">
<ListView
android:id="#+id/listView4"
android:layout_width="match_parent"
android:layout_height="0px"
android:background="#fff"
android:layout_weight="1" >
</ListView>
<Button
android:id="#+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginLeft="313dp"
android:text="Continue" />
</LinearLayout>
Please help me through this I need to submit this by tomorrow.
Use this
convertView = inflater.inflate(R.layout.customlist_massage,null ,false );
Instead this
convertView = inflater.inflate(R.layout.customlist_massage,null );
Why you are extending the adapter class ArrayAdapter.
If You want to show something on listview you have to extend it to BaseAdapter OR Recyclerview Adapter.
You dont have any getCount() method in ArrayAdapter see this example::
public class Adapter extends BaseAdapter {
LayoutInflater li;
ArrayList<String> title, details;
Context con;
DataBaseHelper db;
TextView txttitle, txtdetails, txtDate;
Intent in;
public static int i = 1;
View view;
public Adapter (Context cont, ArrayList<String> news_id, ArrayList<String> news) {
this.title = news_id;
this.details = news;
this.con = cont;
li = (LayoutInflater) con.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
System.out.println("title.size() " + title.size());
return title.size();
}
#Override
public Object getItem(int arg0) {
return arg0;
}
#Override
public long getItemId(int arg0) {
return arg0;
}
#Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
if (arg1 == null) {
arg1 = li.inflate(R.layout.adapter_daycare, null);
txttitle = (TextView) arg1.findViewById(R.id.title);
txtdetails = (TextView) arg1.findViewById(R.id.details);
txtDate = (TextView) arg1.findViewById(R.id.txtdate);
view = (View) arg1.findViewById(R.id.view);
}
String date = new SimpleDateFormat("dd/MM/yyyy").format(new Date());
System.out.println(" formattedDate " + date);
txttitle.setText(title.get(arg0).toString());
txtdetails.setText(details.get(arg0).toString());
txtDate.setText(date);
return arg1;
}
}

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.

Assinging the values of cursor to object

I'm working on showing list of contacts with checkbox. I tried implementing my own cursor adapter and it is checkable. But once I check that value I want the contacts to be stored in ContactPerson object. But when I tried it is showing null pointer exception(That's why I commented out that code). My CursorAdapter code goes like this.
ContactListAcitivity.java
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v4.widget.CursorAdapter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
public class ContactListActivity extends Activity {
ListView list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact_list);
list = (ListView) findViewById(R.id.ListView2);
Cursor cur= getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, null,null,null,null);
startManagingCursor(cur);
String[] result=new String[cur.getCount()];
for (boolean hasData = cur.moveToFirst(); hasData; hasData = cur.moveToNext())
{
ContactPerson contact = new ContactPerson(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)), String.valueOf(cur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
}
stopManagingCursor(cur);
list.setAdapter(new contactAdapter(getApplicationContext(), cur));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.contact_list, menu);
return true;
}
private class ViewHolder{
TextView ContactName;
CheckBox contactCheck;
}
class contactAdapter extends CursorAdapter{
private Cursor cursor;
private Context ccontext;
private LayoutInflater inflater;
public contactAdapter(Context context, Cursor c) {
super(context, c);
// TODO Auto-generated constructor stub
cursor = c;
ccontext = context;
inflater = LayoutInflater.from(context);
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public void bindView(View view, Context arg1, Cursor arg2) {
// TODO Auto-generated method stub
ViewHolder holder = (ViewHolder) view.getTag();
if (holder == null) {
holder = new ViewHolder();
holder.ContactName = (TextView) view.findViewById(R.id.contact_name);
holder.contactCheck = (CheckBox) view.findViewById(R.id.contact_check);
view.setTag(holder);
holder.contactCheck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
CheckBox cb = (CheckBox) v;
cb.setSelected(true);
// ContactPerson contact = (ContactPerson) cb.getTag(); this is the place where it is showing null pointer exception
// Log.i("clicked users", contact.getName());
// contact.setSelected(true);
}
});
}else{
holder = (ViewHolder) view.getTag();
}
// ContactPerson contacts = contactList.get(position);
holder.ContactName.setText(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME)));
// holder.contactCheck.setChecked(contacts.isSelected());
// holder.contactCheck.setTag(contacts);
// holder.ContactName.setText(contacts.getName());
}
#Override
public View newView(Context arg0, Cursor arg1, ViewGroup arg2) {
// TODO Auto-generated method stub
return inflater.inflate(R.layout.checkbox_item, arg2, false);
}
}
}
activity_contact_list.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:background="#000000">
<ListView
android:id="#+id/ListView2"
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=".GroupContactsActivity"
android:layout_alignParentTop="true"
/>
<Button
android:id="#+id/selected_done_1"
android:layout_width="160dp"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:textColor="#FFFFFF"
android:text="Done" />
</RelativeLayout>
checkbox_item.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"
android:background="#000000">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/contact_name"
android:layout_alignParentLeft="true"
android:text="textview"
android:textSize="15sp"
android:textColor="#FFFFFF"
android:gravity="center_horizontal"/>
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:focusable="false"
android:focusableInTouchMode="false"
android:layout_alignParentRight="true"
android:layout_weight="1"
android:id="#+id/contact_check"/>
</RelativeLayout>
Can anyone please suggest me how to use that Contact person class in this adapter.
public class ContactPerson {
String name= null, number = null;
boolean Selected = false;
public ContactPerson(String PersonName, String PhoneNumber){
this.name = PersonName;
this.number= PhoneNumber;
}
public String getName(){
return name;
}
public boolean isSelected(){
return Selected;
}
public void setSelected(boolean selected){
this.Selected = selected;
}
public String getPhoneNumber(){
return number;
}
}
Check this code. It worked for me. Best of luck.
import java.util.ArrayList;
import java.util.Set;
import java.util.TreeSet;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.support.v4.widget.CursorAdapter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class ContactListActivity extends Activity {
ListView list;
ArrayList<ContactPerson> selectedList;
Set<String> phoneID= new TreeSet<String>();;
Button doneButton;
CheckBox cb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact_list);
selectedList = new ArrayList<ContactPerson>();
list = (ListView) findViewById(R.id.ListView2);
doneButton = (Button) findViewById(R.id.selected_done_1);
Cursor cur= getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null,null);
list.setAdapter(new contactAdapter(getApplicationContext(), cur));
doneButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
for (String ids : phoneID) {
Log.d("PhoneIds", ids);
Cursor cursorPhoneNumber = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[]{ContactsContract.CommonDataKinds.Phone.NUMBER},
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ? AND " +
ContactsContract.CommonDataKinds.Phone.TYPE + " = " +
ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE,
new String[]{ids},
null);
Log.d("Number cursor", String.valueOf(cursorPhoneNumber.getCount()));
if (cursorPhoneNumber.moveToFirst()) {
// phoneNumber = cursorPhoneNumber.getString(cursorPhoneNumber.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Log.d("Phone number", cursorPhoneNumber.getString(cursorPhoneNumber.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
}
cursorPhoneNumber.close();
Cursor cursorName = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
new String[]{ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME_PRIMARY},
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " = ? AND " +
ContactsContract.CommonDataKinds.Phone.TYPE + " = " +
ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE,
new String[]{ids},
null);
Log.d("Name cursor", String.valueOf(cursorName.getCount()));
if (cursorName.moveToFirst()) {
Log.d("Phone number", cursorName.getString(cursorName.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME_PRIMARY)));
// Name = cursorName.getString(cursorName.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME_PRIMARY));
}
cursorName.close();
// selectedList.add(new ContactPerson(Name,phoneNumber));
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.contact_list, menu);
return true;
}
private class ViewHolder{
TextView ContactName;
CheckBox contactCheck;
}
class contactAdapter extends CursorAdapter{
String Name, phoneNumber;
private Cursor cursor;
private Context ccontext;
private LayoutInflater inflater;
public contactAdapter(Context context, Cursor c) {
super(context, c);
// TODO Auto-generated constructor stub
cursor = c;
ccontext = context;
inflater = LayoutInflater.from(context);
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public void bindView(View view, Context arg1, Cursor arg2) {
// TODO Auto-generated method stub
ViewHolder holder = (ViewHolder) view.getTag();
if (holder == null) {
holder = new ViewHolder();
holder.ContactName = (TextView) view.findViewById(R.id.contact_name);
holder.contactCheck = (CheckBox) view.findViewById(R.id.contact_check);
view.setTag(holder);
holder.contactCheck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
cb = (CheckBox) v;
cb.setChecked(cb.isChecked());
// ContactPerson selected = (ContactPerson)cb.getTag();
Log.d("selcted", cb.getTag().toString());
if(cb.isChecked()){
phoneID.add(cb.getTag().toString());
}
}
});
}else{
holder = (ViewHolder) view.getTag();
}
holder.ContactName.setText(cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)));
holder.contactCheck.setTag(cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID)));
holder.contactCheck.setChecked(false);
}
#Override
public View newView(Context arg0, Cursor arg1, ViewGroup arg2) {
// TODO Auto-generated method stub
return inflater.inflate(R.layout.checkbox_item, arg2, false);
}
#Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
// TODO Auto-generated method stub
// Log.d("don't know", cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)));
return super.getView(arg0, arg1, arg2);
}
}
}
Here i changed little bit code of your adapter and activity. just look at it:
public class MainActivity extends Activity {
private ArrayList<ContactPerson> arr;
private Context context;
private ListView list;
private ContactArrayAdapter adapter;
private String strName,strNumber;
private View view;
public static boolean[] arrBoolean = null;
#Override
public void onCreate(Bundle savedInstance) {
super.onCreate(savedInstance);
setContentView(R.layout.activity_main);
ProgressDialog pd = new ProgressDialog(this);
list = (ListView)findViewById(R.id.ListView2);
arr = new ArrayList<ContactPerson>();
context = MainActivity.this;
arr = displayContacts();
adapter = new ContactArrayAdapter(this, R.layout.checkbox_item, arr);
list.setAdapter(adapter);
}
public ArrayList<ContactPerson> displayContacts() {
ContentResolver cr = getContentResolver();
Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,null, null, null, null);
ContactPerson contact;
if (cur.getCount() > 0) {
while (cur.moveToNext()) {
contact = new ContactPerson();
String id = cur.getString(cur.getColumnIndex(People._ID));
String name = cur.getString(cur.getColumnIndex(People.DISPLAY_NAME));
ContactPerson cp = new ContactPerson();
cp.setName(name);
cp.setNumber(id);
cp.setSelected(false);
arr.add(cp);
}
}
return arr;
}
//********* Adapter *****
public class ContactArrayAdapter extends ArrayAdapter<ContactPerson> {
// private final List<Contact> list;
private Context context;
private LayoutInflater mInflater;
private List<ContactPerson> list;
public ContactArrayAdapter(Context context, int textViewResourceId,
ArrayList<ContactPerson> stateList) {
super(context, textViewResourceId, stateList);
this.list = new ArrayList<ContactPerson>();
this.list.addAll(stateList);
}
class ViewHolder {
TextView text;
CheckBox checkbox;
}
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
ViewHolder viewHolder = null;
if (view == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R.layout.checkbox_item, null);
viewHolder = new ViewHolder();
viewHolder.text = (TextView) view.findViewById(R.id.contact_name);
viewHolder.checkbox = (CheckBox) view.findViewById(R.id.contact_check);
view.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) view.getTag();
}
final int pos = position;
ContactPerson cp = list.get(position);
viewHolder.text.setText(cp.getName());
viewHolder.checkbox.setChecked(cp.isSelected());
viewHolder.checkbox.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
CheckBox cb = (CheckBox) arg0 ;
list.get(pos).setSelected(cb.isChecked());
System.out.println(cb.isChecked());
System.out.println(list.get(pos).getName());
}
});
//viewHolder.text.setTag(cp);
return view;
}
}
}

How to add EditText in listview and get its value dynamically in all the rows?

I have Checkbox and EditText and a Textview in a listView. It gets value for the text view from a list. Checkbox will be checked dynamically. In the same way EditText also can be entered dynamically. Now my problem is, When i scroll the list view (up and down) after entering the text in the Edit text, I could not get the typed value. I check the check box also like that. But using the position, I set it correct. I Could not know How to set the EditText value to the list properly. Please help me. Here is my code:
main.xml: (Main xml for launch)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/my_list"
android:layout_width="fill_parent"
android:layout_height="250px" />
<Button
android:text="Save"
android:id="#+id/btnSave"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>
row.xml: (ListView Row)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="#+id/label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#+id/label"
android:textSize="30sp"/>
<CheckBox
android:id="#+id/check"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<EditText
android:text=""
android:id="#+id/txtAddress"
android:layout_width="150px"
android:layout_height="wrap_content"/>
</LinearLayout>
Model.Java: (It is the POJO class)
package com.checkboxlistview;
public class Model {
private String name;
private boolean selected;
private String address;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public void setName(String name) {
this.name = name;
}
public Model(String name) {
this.name = name;
}
public String getName() {
return name;
}
public boolean isSelected() {
return selected;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
}
MyAdapter.Java: (This is used to Hold the view in the list view using the converter and holder)
package com.checkboxlistview;
import java.util.List;
import android.app.Activity;
import android.text.Editable;
import android.text.TextWatcher;
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.EditText;
import android.widget.TextView;
public class MyAdapter extends ArrayAdapter<Model> implements TextWatcher {
private final List<Model> list;
private final Activity context;
int listPosititon;
public MyAdapter(Activity context, List<Model> list) {
super(context, R.layout.row, list);
this.context = context;
this.list = list;
}
static class ViewHolder {
protected TextView text;
protected CheckBox checkbox;
protected EditText address;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
listPosititon = position;
ViewHolder viewHolder = null;
if (convertView == null) {
LayoutInflater inflator = context.getLayoutInflater();
convertView = inflator.inflate(R.layout.row, null);
viewHolder = new ViewHolder();
viewHolder.text = (TextView) convertView.findViewById(R.id.label);
viewHolder.checkbox = (CheckBox) convertView
.findViewById(R.id.check);
viewHolder.address = (EditText) convertView
.findViewById(R.id.txtAddress);
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.
}
});
viewHolder.address.addTextChangedListener(this);
convertView.setTag(viewHolder);
convertView.setTag(R.id.label, viewHolder.text);
convertView.setTag(R.id.check, viewHolder.checkbox);
convertView.setTag(R.id.txtAddress, viewHolder.address);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.checkbox.setTag(position); // This line is important.
viewHolder.text.setText(list.get(position).getName());
viewHolder.checkbox.setChecked(list.get(position).isSelected());
if (list.get(position).getAddress() != null) {
viewHolder.address.setText(list.get(position).getAddress() + "");
} else {
viewHolder.address.setText("");
}
return convertView;
}
#Override
public void afterTextChanged(Editable s) {
list.get(listPosititon).setAddress(s.toString());
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
}
}
MainActivity.java (This is the activity):
package com.checkboxlistview;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity {
ListView listView;
Button btnSave;
ArrayAdapter<Model> adapter;
List<Model> list = new ArrayList<Model>();
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
listView = (ListView) findViewById(R.id.my_list);
btnSave = (Button)findViewById(R.id.btnSave);
adapter = new MyAdapter(this,getModel());
listView.setAdapter(adapter);
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
for (int i = 0; i < list.size(); i++) {
Toast.makeText(getBaseContext(), "Name : "+list.get(i).getName() +" Selected: "+list.get(i).isSelected(), Toast.LENGTH_SHORT).show();
}
}
});
}
private List<Model> getModel() {
list.add(new Model("Linux"));
list.add(new Model("Windows7"));
list.add(new Model("Suse"));
list.add(new Model("Eclipse"));
list.add(new Model("Ubuntu"));
list.add(new Model("Solaris"));
list.add(new Model("Android"));
list.add(new Model("iPhone"));
list.add(new Model("Java"));
list.add(new Model(".Net"));
list.add(new Model("PHP"));
return list;
}
}
There is no error in the code. It runs well. I could maintain the checkbox position and display at the same position even I scroll up and down. But I could not get and set the EditText value properly. Please Help me out.
Thanks in advance.
you can achieve this using the custom list view.
find the example of listview with edittext is here
Easy and beautiful solution to handle EditText with listView:
(Does not require holder or RecycleView or anything else)
Brief explaination:
1) In getView method when you inflate the view, apply the myTextWatcher the editText. Pass this EditText to the myTextWatcher()
2) Inside getView Method find that EditText and set position as editText.setTag [Each time. not only when the view was inflated.]
3) Define MyTextWatcher. It should have reference to EditText on which it is applied.
4) myTextWatcher.onTextChanged() will read the tag set to the editText and do the required work
Modify your getView() method of Adapter class:
#Override
public View getView(int position, View convertView, final ViewGroup parent) {
if(convertView==null){
convertView = LayoutInflater.from(getContext()).inflate(R.layout.single_row_layout,parent,false);
EditText et = convertView.findViewById(R.id.idEditText);
et.addTextChangedListener(new MyTextWatcher(et));
}
//This is again required to find reference to EditText... so that 'position' can be applied on to it as 'tag' EACH time.
EditText editText = (EditText) convertView.findViewById(R.id.idEditText);;
//This tag will be used inside onTextChanged()
editText.setTag(position);
}
Define your MyTextWatcher class as:
private class MyTextWatcher implements TextWatcher{
//int position;
EditText et;
public MyTextWatcher(EditText editText){
this.et = editText;
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if(et.getTag()!=null){
// This is required to ensure EditText is edited by user and not through program
if(et.hasFocus()){
int position = (int)et.getTag();
String newText = et.getText()+"";
//Implement your actions here........
//you can get require things/ views from listView.getChildAt(position)..
}
}
}
#Override
public void afterTextChanged(Editable s) {
}
}
Just keep viewHolder.address.setTag(position) and it works perfect cheers.
Adapter Class:
package com.qzick.adapter;
import java.util.ArrayList;
import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.TextView;
import com.example.qzick.R;
import com.qzick.model.Get_All_Class_Model;
public class Get_Class_Adapter extends BaseAdapter {
protected ArrayList<Get_All_Class_Model> get_class_details;
LayoutInflater inflater;
Context context;
private int x = 1;
public Get_Class_Adapter(Context context,
ArrayList<Get_All_Class_Model> get_class_details) {
this.get_class_details = get_class_details;
this.inflater = LayoutInflater.from(context);
this.context = context;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return get_class_details.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return get_class_details.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
convertView = this.inflater.inflate(
R.layout.activity_adapter_class_ll, parent, false);
holder.textclass = (TextView) convertView
.findViewById(R.id.text_class_ll);
holder.txtid = (TextView) convertView.findViewById(R.id.text_id_ll);
holder.checkclass = (CheckBox) convertView
.findViewById(R.id.check_class_LL);
holder.edtsection = (EditText) convertView
.findViewById(R.id.edttxt_addsection_ll);
holder.checkclass
.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
int getPosition = (Integer) buttonView.getTag();
get_class_details.get(getPosition).setChecked(
buttonView.isChecked());
notifyDataSetChanged();
}
});
convertView.setTag(holder);
convertView.setTag(R.id.check_class_LL, holder.checkclass);
convertView.setTag(R.id.edttxt_addsection_ll, holder.edtsection);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.checkclass.setTag(position);
holder.edtsection.setTag(position);
holder.edtsection.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
int pos = (Integer) holder.edtsection.getTag();
get_class_details.get(pos).setEdtsections(s.toString());
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
#Override
public void afterTextChanged(Editable s) {
}
});
holder.txtid.setText(get_class_details.get(position).getId());
holder.textclass.setText(get_class_details.get(position).getText());
holder.edtsection.setText(get_class_details.get(position)
.getEdtsections());
holder.textclass.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
x++;
if (x % 2 == 0) {
holder.checkclass.setChecked(false);
} else {
holder.checkclass.setChecked(true);
}
}
});
holder.checkclass.setChecked(get_class_details.get(position)
.isChecked());
return convertView;
}
private class ViewHolder {
TextView textclass, txtid;`enter code here`
CheckBox checkclass;
EditText edtsection;
}
}

Categories

Resources