save state of checkbox - android

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.

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

how to create custom list of logs with check box in android

how to create custom list of logs with check box in android like this with time date and type of call like missed call,incoming call or outgoing call
Make a view for the row with checkbox and 2 imageviews and whatsoever you need. Set the source of imageview in your adapter according to your data
eg:
if (incoming_call)
logImageView.setImageResource(your_resource);
else {
logImageView.setImageResource(your_other_resource)
}
likewise you can do
I got the answer
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.CallLog;
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;
import com.example.callblockerapp.R;
public class CallLogs extends Activity implements OnItemClickListener,
OnClickListener {
List<String> nameList = new ArrayList<String>();
List<String> numberList = new ArrayList<String>();
List<String> typeList = new ArrayList<String>();
CallLogsAdapter callLogsAdapter;
private Button btnAddCallLogs;
ListView listViewAddFromLogs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.add_from_call_logs);
getAllLogContacts(this.getContentResolver());
listViewAddFromLogs = (ListView) findViewById(R.id.listViewAddFromLogs);
callLogsAdapter = new CallLogsAdapter();
listViewAddFromLogs.setAdapter(callLogsAdapter);
listViewAddFromLogs.setOnItemClickListener(this);
listViewAddFromLogs.setItemsCanFocus(false);
listViewAddFromLogs.setTextFilterEnabled(true);
btnAddCallLogs = (Button) findViewById(R.id.btnAddFromCallLogs);
btnAddCallLogs.setOnClickListener(this);
}
#Override
public void onClick(View v) {
StringBuilder checkedcontacts = new StringBuilder();
for (int i = 0; i < nameList.size(); i++)
{
if (callLogsAdapter.mCheckStates.get(i) == true) {
checkedcontacts.append(nameList.get(i).toString());
checkedcontacts.append("\n");
} else {
}
}
Toast.makeText(CallLogs.this, checkedcontacts, Toast.LENGTH_LONG)
.show();
}
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
// TODO Auto-generated method stub
callLogsAdapter.toggle(arg2);
}
public void getAllLogContacts(ContentResolver cr) {
StringBuffer sb = new StringBuffer();
Cursor managedCursor = managedQuery(CallLog.Calls.CONTENT_URI, null,
null, null, null);
int name = managedCursor.getColumnIndex(CallLog.Calls.CACHED_NAME);
int number = managedCursor.getColumnIndex(CallLog.Calls.NUMBER);
int type = managedCursor.getColumnIndex(CallLog.Calls.TYPE);
// int date = managedCursor.getColumnIndex(CallLog.Calls.DATE);
// int duration = managedCursor.getColumnIndex(CallLog.Calls.DURATION);
while (managedCursor.moveToNext()) {
String nameLog = managedCursor.getString(name);
String phNumber = managedCursor.getString(number);
String callType = managedCursor.getString(type);
// String callDate = managedCursor.getString(date);
// Date callDayTime = new Date(Long.valueOf(callDate));
// String callDuration = managedCursor.getString(duration);
String dir = null;
int dircode = Integer.parseInt(callType);
switch (dircode) {
case CallLog.Calls.OUTGOING_TYPE:
dir = "OUTGOING";
break;
case CallLog.Calls.INCOMING_TYPE:
dir = "INCOMING";
break;
case CallLog.Calls.MISSED_TYPE:
dir = "MISSED";
break;
}
nameList.add(nameLog);
numberList.add(phNumber);
typeList.add(dir);
sb.append("\nPhone Number:--- " + phNumber + " \nCall Type:--- "
+ dir);
sb.append("\n----------------------------------");
}
managedCursor.close();
// call.setText(sb);
}
class CallLogsAdapter extends BaseAdapter implements
CompoundButton.OnCheckedChangeListener {
private SparseBooleanArray mCheckStates;
LayoutInflater mInflater;
private TextView txtName, txtNumber, txtType;
CheckBox cb;
CallLogsAdapter() {
mCheckStates = new SparseBooleanArray(nameList.size());
mInflater = (LayoutInflater) CallLogs.this
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return nameList.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.add_from_call_logs_row, null);
txtName = (TextView) vi.findViewById(R.id.txtCallLogsName);
txtNumber = (TextView) vi.findViewById(R.id.txtCallLogsNumber);
txtType = (TextView) vi.findViewById(R.id.txtCallLogsType);
cb = (CheckBox) vi.findViewById(R.id.chkBoxCallLogs);
txtName.setText("Name :" + nameList.get(position));
txtNumber.setText("Phone No :" + numberList.get(position));
txtType.setText("Type :- " + typeList.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);
}
}
}

How to solve a ResourcesNotFoundException in Android

This is my code , I have a problem ,error message about ResourcesNotFoundException this is a piece of code to view employees it has 2 buttons one to do delete and the other to do update.
I don't know the reason of this exception.
package com.example.task_9;
import java.util.ArrayList;
import com.example.task_9.my_dataBase.employees_con;
import com.example.task_9.my_dataBase.my_database;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class manage extends Activity {
ListView listview;
TextView totalrecords,tv;
//my_database db;
public ArrayList<employees> emp_list ;
employees_con con;
//Button logout;
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
setContentView(R.layout.manage);
tv = (TextView) findViewById(R.id.textView1);
tv.setText("Employees Record:");
totalrecords = (TextView) findViewById(R.id.textView2);
listview = (ListView) findViewById(R.id.listView1);
// logout=(Button) findViewById(R.id.button1);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
emp_list = new ArrayList<employees>();
emp_list.clear();
con = new employees_con(this);
// db = new my_database(getApplicationContext());
// db.getWritableDatabase();
ArrayList<employees> e_list =con.getAllData() ;
for (int i = 0; i < e_list.size(); i++) {
Log.d("for_getall ", "ok ");
int e_id = e_list.get(i).getId();
Log.d("fun_getall ", "ok ");
// System.out.println("tidno>>>>>" + tidno);
String e_name = e_list.get(i).getUser_name();
String e_password = e_list.get(i).getPassword();
int e_age = e_list.get(i).getAge();
int e_status = e_list.get(i).getStatus();
Log.d("fun_getall ", "ok ");
employees emp_model = new employees();
emp_model.setId(e_id);
emp_model.setUser_name(e_name);
emp_model.setPassword(e_password);
emp_model.setAge(e_age);
emp_model.setStatus(e_status);
Log.d("addlist ", "ok ");
emp_list.add(emp_model);
}
Log.d("out for ", "ok ");
totalrecords.setText("Total Records :-" + emp_list.size());
listview.setAdapter(new ListAdapter(this));
con.close();
}
private class ListAdapter extends BaseAdapter {
//ArrayList<employees> data=new ArrayList<employees>();
Context contxt;
TextView id;
TextView user_name;
TextView password;
TextView age;
TextView status;
ImageView img;
employees obj;
LayoutInflater inflater;
public ListAdapter(Context context) {
// TODO Auto-generated constructor stub
contxt=context;
inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return emp_list.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 position;
}
#Override
public View getView(int position, View v, ViewGroup parent) {
// TODO Auto-generated method stub
/*if (v == null) {
v = inflater.inflate(R.layout.view, null);}*/
if (v == null)
{
LayoutInflater vi = (LayoutInflater)contxt.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.view, null); // album_list.xml this layout of the custom listview
Log.d("view if", "ok ");
}
id=(TextView) v.findViewById(R.id.textView6);
user_name=(TextView) v.findViewById(R.id.textView7);
password=(TextView) v.findViewById(R.id.textView8);
age=(TextView) v.findViewById(R.id.textView9);
status=(TextView) v.findViewById(R.id.textView10);
img =(ImageView) v.findViewById(R.id.imageView1);
Log.d("out if", "ok ");
obj = emp_list.get(position);
user_name.setText(obj.getUser_name());
id.setText(obj.getId());
password.setText(obj.getPassword());
age.setText(obj.getAge());
status.setText(obj.getStatus());
Log.d("view else ", "ok ");
final int temp = position;
(v.findViewById(R.id.button1))
.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
int emp_id=emp_list.get(temp).getId();
String emp_name = emp_list.get(temp).getUser_name();
String emp_password = emp_list.get(temp).getPassword();
int emp_age=emp_list.get(temp).getAge();
int emp_status=emp_list.get(temp).getStatus();
Intent intent = new Intent(manage.this,update.class);
Bundle bundle = new Bundle();
bundle.putInt("id", emp_id);
bundle.putString("name", emp_name);
bundle.putString("password", emp_password);
bundle.putInt("age", emp_age);
bundle.putInt("status", emp_status);
intent.putExtras(bundle);
startActivity(intent);
}
});
(v.findViewById(R.id.button2))
.setOnClickListener(new OnClickListener() {
employees_con con=new employees_con(contxt);
public void onClick(View arg0) {
AlertDialog.Builder alertbox = new AlertDialog.Builder(manage.this);
alertbox.setCancelable(true);
alertbox.setMessage("Are you sure you want to delete ?");
alertbox.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface arg0, int arg1) {
con.DeleteEmp(emp_list.get(temp).getUser_name().toString());
con.close();
manage.this.onResume();
Toast.makeText(
getApplicationContext(),
"Record Deleted...",
Toast.LENGTH_SHORT).show();
}
});
alertbox.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface arg0, int arg1) {
Toast.makeText(
getApplicationContext(),
"No Clicked...",
Toast.LENGTH_SHORT).show();
}
});
alertbox.show();
}
});
return v;
}
}
}
}
Change
id.setText(obj.getId());
with
id.setText(String.valueOf(obj.getId()));
if you pass an int as argument for a TextView android will look for a String with id the int you provide. If it does not found throws an exception
One important this is that you should use Activity.onCreate() method in place of Activity.onStart().

Not able to see text in ListView

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

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