Not able to see text in ListView - android

I am using ListActivity to display simple text with SimpleCursorAdapter to get the texts from my database. I have tried to debug the problem and found that the cursor is successfully fetching the result but the text is not displayed in the ListView.
Following is the ListActivity code I am using.
public class MyListActivity extends ListActivity{
Cursor myCursor;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
myCursor = getData();
startManagingCursor(myCursor);
ListAdapter myAdapter = new SimpleCursorAdapter(this, R.layout.display_details, myCursor, new String[]{MyDbHelper.ID_FIELD, MyDbHelper.NAME_FIELD}, new int[]{R.id.row_id, R.id.row_name});
setListAdapter(myAdapter);
}
private Cursor getData() {
return MyDBHelper.getRoutes();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
routesCursor.close();
}
}
and following is my xml file for each row in ListView
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/row_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/row_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/row_id"
android:layout_toRightOf="#+id/row_id"
android:textAppearance="?android:attr/textAppearanceLarge" />
</RelativeLayout>
and my layout for ListActivity is as following
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ListView android:id="#+id/list" android:layout_width="fill_parent" android:layout_height="fill_parent">
</ListView>
</RelativeLayout>
Please provide me the solution. Thanks in advance.

This code can help your problem.
package com.example.getkontakdata;
import java.util.ArrayList;
import java.util.List;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnItemClickListener {
List<String> name1 = new ArrayList<String>();
List<String> phno1 = new ArrayList<String>();
MyAdapter ma;
Button select;
CheckBox cb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getAllCallLogs(this.getContentResolver());
final ListView lv= (ListView) findViewById(R.id.lv);
cb = (CheckBox) findViewById(R.id.checkBox1);
ma = new MyAdapter();
lv.setAdapter((ListAdapter) ma);
lv.setOnItemClickListener(this);
lv.setItemsCanFocus(false);
lv.setTextFilterEnabled(true);
// adding
select = (Button) findViewById(R.id.button1);
select.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
StringBuilder checkedcontacts= new StringBuilder();
System.out.println(".............." + ma.mCheckStates.size());
for(int i = 0; i < phno1.size(); i++) {
if(ma.mCheckStates.get(i) == true) {
checkedcontacts.append(phno1.get(i).toString());
checkedcontacts.append(";");
} else {
System.out.println(".. Not Checked ......" + phno1.get(i).toString());
}
}
}
});
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
ma.toggle(arg2);
}
public void getAllCallLogs(ContentResolver cr) {
Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,null,null, null);
while (phones.moveToNext()) {
String name=phones.getString
(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones.getString
(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
//System.out.println(".................." + phoneNumber);
name1.add(name);
phno1.add(phoneNumber);
}
phones.close();
}
class MyAdapter extends BaseAdapter implements CompoundButton.OnCheckedChangeListener {
private SparseBooleanArray mCheckStates;
//private SparseBooleanArray nCheckStates;
LayoutInflater mInflater;
TextView tv1,tv;
CheckBox cb;
MyAdapter() {
mCheckStates = new SparseBooleanArray(name1.size());
mCheckStates = new SparseBooleanArray(phno1.size());
mInflater = (LayoutInflater)MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public String get(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return name1.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View vi=convertView;
if(convertView==null)
vi = mInflater.inflate(R.layout.row, null);
TextView tv= (TextView) vi.findViewById(R.id.textView1);
tv1= (TextView) vi.findViewById(R.id.textView2);
cb = (CheckBox) vi.findViewById(R.id.checkBox1);
tv.setText("Nama : "+ name1.get(position));
tv1.setText("Nomor Kontak : "+ phno1.get(position));
cb.setTag(position);
cb.setChecked(mCheckStates.get(position, false));
cb.setOnCheckedChangeListener((OnCheckedChangeListener) this);
return vi;
}
public boolean isChecked(int position) {
return mCheckStates.get(position, false);
}
public void setChecked(int position, boolean isChecked) {
mCheckStates.put(position, isChecked);
System.out.println("hello...........");
notifyDataSetChanged();
}
public void toggle(int position) {
setChecked(position, !isChecked(position));
}
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
}
}

Related

Accessing an element-Button in grid view

I am supposed to access a button of an element in a grid view and supposed to capture the onItemClick() activity of that button, but somehow I am not able to do it. Help me out. I am posting my code below. Please check it.
package com.nik.cardone;
import java.util.ArrayList;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.GridView;
import android.widget.TextView;
public class Fragment2 extends Fragment{
GridView fragment2Grid;
POJOMenuGrid pojo;
ArrayList<POJOMenuGrid> arr;
String[] name = {"Manchow Soup","Clear Soup","Mushroom Soup","Corn Soup","Tomato Soup"};
String[] desc = {"Soya water with capsicum , carrots , medium spicy"};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
View v = inflater.inflate(R.layout.new_order_fragment_2, null);
initialize();
fragment2Grid = (GridView)v.findViewById(R.id.fragment2Grid);
fragment2Grid.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
View v = arg0.getChildAt(arg2);
// TODO Auto-generated method stub
System.out.println("In grid :");
}
});
for(int i=0;i<5;i++){
arr.add(new POJOMenuGrid(name[i], desc[0], R.drawable.t2));
}
System.out.println(arr.get(0).getName()+" "+arr.get(0).getDescription()+" ");
CustomGridAdapter adapter = new CustomGridAdapter(v.getContext(), arr);
fragment2Grid.setAdapter(adapter);
System.out.println("adapter set");
return v;
}
private void initialize() {
// TODO Auto-generated method stub
arr = new ArrayList<POJOMenuGrid>();
}
}
Custom Adapter
package com.nik.cardone;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
public class CustomGridAdapter extends BaseAdapter{
Context context;
ArrayList<POJOMenuGrid> arr;
LayoutInflater inflater;
TextView itemName;
TextView itemDescription;
ImageView itemImage;
Button plus;
Button minus;
TextView counter;
public CustomGridAdapter(Context context, ArrayList<POJOMenuGrid> arr) {
super();
this.context = context;
this.arr = arr;
inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
System.out.println("in constructor");
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return arr.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return arr.get(arg0);
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return arg0;
}
#Override
public View getView(int arg0, View arg1, ViewGroup arg2) {
// TODO Auto-generated method stub
System.out.println("in adapter 1");
arg1 = inflater.inflate(R.layout.grid_single_item, null);
System.out.println("in adapter 2");
itemName = (TextView)arg1.findViewById(R.id.itemName);
itemDescription = (TextView)arg1.findViewById(R.id.itemDescription);
//counter = (TextView)arg1.findViewById(R.id.counter);
itemImage = (ImageView)arg1.findViewById(R.id.itemImage);
plus = (Button)arg1.findViewById(R.id.plus);
minus = (Button)arg1.findViewById(R.id.minus);
plus.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
System.out.println("In plus :");
// TODO Auto-generated method stub
TextView counter = (TextView)arg0.findViewById(R.id.counter);
int counter1 = Integer.parseInt(counter.getText().toString());
counter1++;
counter.setText(""+counter1);
}
});
minus.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
TextView counter = (TextView)arg0.findViewById(R.id.counter);
int counter1 = Integer.parseInt(counter.getText().toString());
counter1--;
counter.setText(""+counter1);
}
});
System.out.println("in adapter 3");
itemName.setText(arr.get(arg0).getName());
itemDescription.setText(arr.get(arg0).getDescription());
itemImage.setImageResource(arr.get(arg0).getImage());
System.out.println("in adapter 4");
return arg1;
}
}

contact on list view with select all option and search option on android

contact on list view with select all option and search option on android
i have tried a lot of ways but no matter to find a list view with name,phone no and check box for everyone and also a select all button and search option
public void onTextChanged(CharSequence s,int start, int before, int count)
{
textlength = et.getText().length();
// et.setText(textlength);
if(et.getText().toString().equalsIgnoreCase("helloo")){
// Toast.makeText(getApplicationContext(),"jd",1000).show();
for (int i = 0; i < name1.size(); i++)
{
if (textlength <= name1.size())
{
Toast.makeText(getApplicationContext(),"searching.....inside",1000).show();
if(et.getText().toString().equalsIgnoreCase((String)((CharSequence) name1).subSequence(0,textlength)))
{
// array_sort.addAll(name1);
}
}
if(et.getText().toString().equalsIgnoreCase(
(String)(CharSequence) name1)){
Toast.makeText(getApplicationContext(),"searching.....",1000).show();
}
}
lv.setAdapter(new ArrayAdapter<String>
(contact_fetch.this,
android.R.layout.simple_list_item_1, array_sort));
}
}
});
I had the same problem.Finally I solved with this code. Hope It will help you :)
//layout function
public void lay_out(List<String> exp1,int k){
LayoutInflater layoutInflater =
(LayoutInflater) getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
container.removeAllViews();
for(int i=0;i<exp1.size();i++){
final View addView = layoutInflater.inflate(R.layout.row, null);
TextView tv=(TextView)addView.findViewById(R.id.textView1);
final CheckBox cb=(CheckBox) addView.findViewById(R.id.checkbox1);
if(k==0)
{
cb.setChecked(false);
}
else
{
cb.setChecked(true);
}
tv.setText(name1.get(i));
cb.setText(phno1.get(i));
container.addView(addView);
cb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// Toast.makeText(getApplicationContext(),cb.getText().toString(),10).show();
if(cb.isChecked()==true){
if(checkedcontacts.length()<0)
{
for(int i=0;i<=checkedcontacts.length();i++)
{
if(!checkedcontacts.equals(cb.getText().toString()))
{
// insertion
checkedcontacts.append(cb.getText().toString());
checkedcontacts.append("\n");
}
}
}
else{
checkedcontacts.append(cb.getText().toString());
checkedcontacts.append("\n");
}
}
else if(cb.isChecked()==false){
s_all.setChecked(false);
try{
Toast.makeText(getApplicationContext(),cb.getText().toString(),10).show();
//Pattern.compile(cb.getText().toString()).matcher(checkedcontacts).replaceAll("");
checkedcontacts.delete(checkedcontacts.indexOf(cb.getText().toString()),
cb.getText().toString().length());
}
catch(Exception e){
System.out.println("error on array"+e);
}
}
}
});
container.setVisibility(View.VISIBLE);
}
}
Try this code to get all contacts with checkboxex:
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class Display extends Activity implements OnItemClickListener {
List<String> name1 = new ArrayList<String>();
List<String> phno1 = new ArrayList<String>();
MyAdapter ma;
Button select;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.display);
getAllContacts(this.getContentResolver());
ListView lv = (ListView) findViewById(R.id.lv);
ma = new MyAdapter();
lv.setAdapter(ma);
lv.setOnItemClickListener(this);
lv.setItemsCanFocus(false);
lv.setTextFilterEnabled(true);
// adding
select = (Button) findViewById(R.id.button1);
select.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
StringBuilder checkedcontacts = new StringBuilder();
System.out.println(".............." + ma.mCheckStates.size());
for (int i = 0; i < name1.size(); i++)
{
if (ma.mCheckStates.get(i) == true) {
checkedcontacts.append(name1.get(i).toString());
checkedcontacts.append("\n");
} else {
System.out.println("Not Checked......"
+ name1.get(i).toString());
}
}
Toast.makeText(Display.this, checkedcontacts, 1000).show();
}
});
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
ma.toggle(arg2);
}
public void getAllContacts(ContentResolver cr) {
Cursor phones = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,
null, null);
while (phones.moveToNext()) {
String name = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
System.out.println(".................." + phoneNumber);
name1.add(name);
phno1.add(phoneNumber);
}
phones.close();
}
class MyAdapter extends BaseAdapter implements
CompoundButton.OnCheckedChangeListener {
private SparseBooleanArray mCheckStates;
LayoutInflater mInflater;
TextView tv1, tv;
CheckBox cb;
MyAdapter() {
mCheckStates = new SparseBooleanArray(name1.size());
mInflater = (LayoutInflater) Display.this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return name1.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
// TODO Auto-generated method stub
View vi = convertView;
if (convertView == null)
vi = mInflater.inflate(R.layout.row, null);
TextView tv = (TextView) vi.findViewById(R.id.contact_name);
tv1 = (TextView) vi.findViewById(R.id.phone_number);
cb = (CheckBox) vi.findViewById(R.id.checkBox_id);
tv.setText("Name :" + name1.get(position));
tv1.setText("Phone No :" + phno1.get(position));
cb.setTag(position);
cb.setChecked(mCheckStates.get(position, false));
cb.setOnCheckedChangeListener(this);
return vi;
}
public boolean isChecked(int position) {
return mCheckStates.get(position, false);
}
public void setChecked(int position, boolean isChecked) {
mCheckStates.put(position, isChecked);
System.out.println("hello...........");
notifyDataSetChanged();
}
public void toggle(int position) {
setChecked(position, !isChecked(position));
}
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
}
}
dispay.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"
tools:context=".MainActivity" >
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/button1"
android:id="#+id/lv"/>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="Select" />
</RelativeLayout>
Row.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/contact_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="John Doe"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/phone_number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/contact_name"
android:text="(999)999-9999"
android:textAppearance="?android:attr/textAppearanceMedium" />
<CheckBox
android:id="#+id/checkBox_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true" />
</RelativeLayout>

save state of checkbox

i havetwo activty in which activity b has the contact details when user select the checkbox,data is stored in the string in the activity a,for more selction when user goes back to activity b,previously selected contacts are shown checked,that means their state ramain saved,how to do that
MainActivity.java
package com.example.smscampaign;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import android.app.ActionBar;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.os.Parcelable;
import android.provider.ContactsContract;
import android.telephony.gsm.SmsManager;
import android.util.SparseBooleanArray;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class MainActivity extends Activity implements OnItemClickListener {
ArrayList<String> name1 = new ArrayList<String>();
ArrayList<String> phno1 = new ArrayList<String>();
ArrayList<String> phno0 = new ArrayList<String>();
MyAdapter ma;
Button send;
ListView lv ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActionBar actionBar = getActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
setContentView(R.layout.get);
TextView txt=(TextView) findViewById(R.id.textView1);
getAllCallLogs(this.getContentResolver());
lv = (ListView) findViewById(R.id.lv);
ma = new MyAdapter();
lv.setAdapter(ma);
lv.setOnItemClickListener(this);
lv.setItemsCanFocus(false);
lv.setTextFilterEnabled(true);
}
/* #Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
// Save ListView state
Parcelable state = lv.onSaveInstanceState();
// Set new items
lv.setAdapter(Baseadapter);
// Restore previous state (including selected item index and scroll position)
lv.onRestoreInstanceState(state);
}*/
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
getMenuInflater().inflate(R.menu.contact_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.addPage:
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
StringBuilder checkedcontacts = new StringBuilder();
System.out.println( ma.mCheckStates.size());
for (int i = 0; i < name1.size(); i++)
{
if (ma.mCheckStates.get(i) == true) {
phno0.add(phno1.get(i).toString());
checkedcontacts.append(name1.get(i).toString());
checkedcontacts.append("\n");
} else {
System.out.println("..Not Checked......"
+ name1.get(i).toString());
}
}
//Toast.makeText(MainActivity.this, checkedcontacts, 1000).show();
Intent returnIntent = new Intent();
returnIntent.putStringArrayListExtra("name", phno0);
setResult(RESULT_OK, returnIntent);
finish();
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
ma.toggle(arg2);
}
public void getAllCallLogs(ContentResolver cr) {
Cursor phones = cr.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null,
null, null);
while (phones.moveToNext()) {
String name = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String phoneNumber = phones
.getString(phones
.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
System.out.println( phoneNumber);
name1.add(name);
phno1.add(phoneNumber);
}
phones.close();
}
class MyAdapter extends BaseAdapter implements
CompoundButton.OnCheckedChangeListener {
private SparseBooleanArray mCheckStates;
LayoutInflater mInflater;
TextView tv1, tv;
CheckBox cb;
MyAdapter() {
mCheckStates = new SparseBooleanArray(name1.size());
mInflater = (LayoutInflater) MainActivity.this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
// Save ListView state
#Override
public int getCount() {
// TODO Auto-generated method stub
return name1.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView,
ViewGroup parent) {
// TODO Auto-generated method stub
View vi = convertView;
if (convertView == null)
vi = mInflater.inflate(R.layout.row, null);
tv = (TextView) vi.findViewById(R.id.textView1);
tv1 = (TextView) vi.findViewById(R.id.textView2);
cb = (CheckBox) vi.findViewById(R.id.checkBox1);
tv.setText(name1.get(position));
tv1.setText( phno1.get(position));
cb.setTag(position);
cb.setChecked(mCheckStates.get(position, false));
cb.setOnCheckedChangeListener(this);
return vi;
}
public boolean isChecked(int position) {
return mCheckStates.get(position, false);
}
public void setChecked(int position, boolean isChecked) {
mCheckStates.put(position, isChecked);
}
public void toggle(int position) {
setChecked(position, !isChecked(position));
}
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
}
}
Pass String In Intent.
try this Code For Ex:
You need to pass it as an Intent
ArrayList<String> mylist = new ArrayList<String>();
Intent intent = new Intent(ActivityName.this, Second.class);
intent.putStringArrayListExtra("key", mylist);
startActivity(intent);
Then extract it from your new activity like this:
Intent i = getIntent();
ArrayList<String> list = i.getStringArrayListExtra("key");
hope this helps 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;
}
}
}

getting problem to add items in listview from spinner item selection on button click

Hello friends i m getting problem to add items in listview from spinner item selection on button. Here i m providing code please help me to get rid of the problem.
import java.util.ArrayList;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.Adapter;
public class DefectlistviewActivity extends ListActivity {
ArrayList<String> listItems=new ArrayList<String>();
ArrayAdapter<String> adapter;
/** Called when the activity is first created. */
ListView defectDisplay;
Spinner spinner;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
spinner = (Spinner)this.findViewById(R.id.Defect);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.defects_array, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
// defectDisplay = (ListView) findViewById(R.id.list);
Button add = (Button) findViewById(R.id.Add_new_Defect_Button);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
startActivity(new Intent("com.android.HCS.AddDialog"));
}
});
spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
}
private class EfficientAdapter extends BaseAdapter {
TextView tv;
// private LayoutInflater mInflater;
Context context;
#Override
public int getCount() {
// TODO Auto-generated method stub
return 0;
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View row, ViewGroup convertView) {
// TODO Auto-generated method stub
LayoutInflater mInflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// mInflater = LayoutInflater.from(context);
if (null == convertView) {
row = mInflater.inflate(R.layout.listview, null);
} else {
row = convertView;
}
tv = (TextView) row.findViewById(R.id.Defect1);
//tv.setText(getItem(position));
String itemVal = (String)getItem(position);
tv.setText(itemVal);
return row;
}
}
public class MyOnItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(final AdapterView<?> parent,
final View view, final int pos, long id) {
Button add_defect = (Button) findViewById(R.id.Add_Defect_Button);
add_defect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Toast.makeText(parent.getContext(),
parent.getItemAtPosition(pos).toString(), Toast.LENGTH_LONG).show();
setListAdapter(new EfficientAdapter());
}
});
}
public void onNothingSelected(AdapterView parent) {
// Do nothing.
}
}
}
Your getCount() function in EfficientAdapter is returning 0. So you wont get any callback to getView(). Also getItem(position) is returning null which you trying to set to textview in getView funcion of EfficientAdapter .
I guess you should have a list set to EfficientAdapter who's size should be returned in getCount() and on spinner operation you add your addtional data to the list and notify your list adaptor ie..,EfficientAdapter

Categories

Resources