I create checkboxes dynamically & i want to bind that checkboxes to listview.
How can I do that?
Here i give my code--
public class HomeActivity extends ListActivity{
CheckBox[] chk;
ListView lv1;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
lv1=(ListView)findViewById(R.id.listTasks);
tv1=(TextView) findViewById(R.id.tvMsg);
The database section:
db = new DBAdapter(HomeActivity.this);
db.open();//int[] id=new int[]{Integer.parseInt(DBAdapter.ID)};
Cursor cr=db.getUncompletedTask();//my database function to retrieve values to create checkboxes
if (cr.moveToFirst()) {
do {
String[] str=new String[2];
str[0]=cr.getString(0);
str[1]=cr.getString(1);
al.add(str);
} while (cr.moveToNext());
}
startManagingCursor(cr);
String[] tasks = new String[] { DBAdapter.KEY_TODO };
Creation of checkbox:
int[] idchk=new int[al.size()];//here i am creating checkbox dynamicaly
if (al.size() != 0) {
chk = new CheckBox[al.size()];
System.out.println(al.size());
for (int i = 0; i < al.size(); i++) {
String[] s = (String[]) al.get(i);
System.out.println("ID: "+s[0]);
Task_Id = Integer.parseInt(s[0]);
Task_Nm = s[1];
chk[i] = new CheckBox(HomeActivity.this);
System.out.println(i +"task id"+Task_Id +"parseint"+Integer.parseInt(s[0]+chk[i].getText().toString()));
chk[i].setId(Task_Id);
idchk[i]=Task_Id;
chk[i].setText(Task_Nm);
//lv1.addView(chk[i]);
//setContentView(lv1);
}}}
Here what can i write here so that this dynamically created checkboxes will be bind to listview
What if you use the default listview of android with checkbox.
By using :
setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_checked, COUNTRIES));
where COUNTRIES is static final string array that contains the item to show..
You can use customized ListView whose rows contains CheckBox. Create your own adapter extending ArrayAdapter and it's overridden method getView create your checkboxes.
Related
I have a dummy listview that I have setup in my app that uses the following code:
public class Roster extends Activity {
private ListView mainListView ;
private ArrayAdapter<String> listAdapter ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_roster);
// ListView resource.
mainListView = (ListView) findViewById( R.id.rosterListView );
// List of names.
String[] players = new String[] { "Dude1", "Guy2"};
ArrayList<String> playerlist = new ArrayList<String>();
playerlist.addAll( Arrays.asList(players) );
//ArrayAdapter using the list.
listAdapter = new ArrayAdapter<String>(this, R.layout.rosterrow, playerlist);
// Add more Players, If you passed a String[] instead of a List<String>
// into the ArrayAdapter constructor, you must not add more items.
// Otherwise an exception will occur.
listAdapter.add( "Person8" );
// Set the ArrayAdapter as the ListView's adapter.
mainListView.setAdapter( listAdapter );
getActionBar().setDisplayHomeAsUpEnabled(true);
}
which gives me a listview of three players.
I now want to use the json object to populate the list instead of using a string. How can I populate the list using my json object?
Try to get the value of Json by key and put it in to string array.
JsonObject myjsondata = new JsonObject(jsondata.toString());
String[] players = new String[] {myjsondata.getString("key") , myjsondata.getString("key1")};
The problem i am facing is that i have my code is executing "else" block even when the "if " condition is true.
public class MsgNewPackage extends Activity {
private DatabaseHandler dbhandler;
private SimpleCursorAdapter dataAdapter;
private ListView listView;
String PKG_NAME,PKG_DUR,PKG_PRICE,PKG_ITEMS;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_msg_new_package);
dbhandler = new DatabaseHandler(this);
displayListView();
}
private void displayListView()
{
String check= "Mobilink";
Intent intent = getIntent();
String conn = intent.getStringExtra("NET_CONN");
// Toast.makeText(getApplicationContext(), conn, Toast.LENGTH_SHORT).show();
if(conn == check)
{
Cursor cursor = dbhandler.fetchAllMOBSMSPackages();
String[] columns = new String[]{DatabaseHandler.KEY_PKG_NAME,DatabaseHandler.KEY_NO_OF_FREE_ITEMS,DatabaseHandler.KEY_DURATION,DatabaseHandler.KEY_CHARGES};
// the XML defined views which the data will be bound to
int[] to = new int[] { R.id.title,R.id.no_of_item,R.id.duration,R.id.pkgcharges};
// create the adapter using the cursor pointing to the desired data
//as well as the layout information
dataAdapter = new SimpleCursorAdapter(this, R.layout.list_row2, cursor,columns,to);
listView = (ListView) findViewById(R.id.listView1);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
}
else
{
Cursor cursor = dbhandler.fetchAllSMSPackages();
String[] columns = new String[]{DatabaseHandler.KEY_PKG_NAME,DatabaseHandler.KEY_NO_OF_FREE_ITEMS,DatabaseHandler.KEY_DURATION,DatabaseHandler.KEY_CHARGES};
// the XML defined views which the data will be bound to
int[] to = new int[] { R.id.title,R.id.no_of_item,R.id.duration,R.id.pkgcharges};
// create the adapter using the cursor pointing to the desired data
//as well as the layout information
dataAdapter = new SimpleCursorAdapter(this, R.layout.list_row2, cursor,columns,to);
listView = (ListView) findViewById(R.id.listView1);
// Assign adapter to ListView
listView.setAdapter(dataAdapter);
}
The toast displays that conn has "Mobilink" but the listview gets populated with results of fetchAllSMSPackages() (i.e function called in else block ) which should not be the case. Pleas help.
Try using conn.equals(check) instead of conn == check.
Strings in Java are objects, and not primitives, so you cannot compare their value using ==. This will compare the object as a whole, and not the text.
You should use .equals() when comparing String values. Not ==.
Try using:
conn.equals(check);
I have a list view that displays records from a database. Each row in the listview has a checkbox. How do I...
Create a toast message displaying the value of the selected item?
Identify the records selected by the user in the listview?
Iterate through each selected item and delete only the rows selected in the listview from the database?
I've been following this helpful tutorial here: //http://www.vogella.com/articles/AndroidSQLite/article.html
public class PhoneNumberDataBaseListView extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
NumbersDataSource datasource = new NumbersDataSource(this);
datasource.open();
String number = "123";
datasource.createNumber(number);
List<Number> values = datasource.getAllNumbers();
ArrayAdapter<Number> adapter = new ArrayAdapter<Number>(this, android.R.layout.simple_list_item_multiple_choice, values);
setListAdapter(adapter);
}
public void deleteNumber() {
NumbersDataSource datasource = new NumbersDataSource(this);
datasource.open();
ListView LV = (ListView) findViewById(android.R.id.list);
List<Number> values = datasource.getAllNumbers();
ArrayAdapter<Number> adapter = new ArrayAdapter<Number>(this, android.R.layout.simple_list_item_multiple_choice, values);
setListAdapter(adapter);
SparseBooleanArray checkedItems = LV.getCheckedItemPositions();
for (int i = 0; i < checkedItems.size(); i++) {
if(checkedItems.valueAt(i)) {
Number item = adapter.getItem(i);
Toast t = Toast.makeText(this, item.getNumber().toString(), Toast.LENGTH_LONG);
t.show();
}
}
}
Method getCheckedItemPositions() returns SparseBooleanArray that indicates which items are checked (if item on specific position is checked, method valueAt(position) invoked on that array returns true). Class DBAdapter from tutorial you are following provides you with deleteTitle(long rowId) method which you should use to acheive what you want.Therefore your code should look more or less like this:
SparseBooleanArray checkedItems = listView.getCheckedItemPositions();
for (int i = 0; i < checkedItems.size(); i++) {
if(checkedItems.valueAt(i)) {
db.deleteTitle(adapter.getItemId(i));
}
}
Of course SimpleCursorAdapter and DBAdapter should be stored in object attributes so that you have access to them from both methods (onCreate and deleteRecord). By the way, View parameter passed to deleteRecord method is not needed.
I got this piece of code that creates new TextView, then adds it to ArrayList<View> and when it is finished adding TextViews to Array it sets adds that Array into ListView. But somehow my ListView is appearing empty. Any idea what am I doing wrong?
Here is the code:
ListView lv = (ListView) findViewById(R.id.listView1);
ArrayList<View> textvs = new ArrayList<View>();
for (int i=0; i<10;i++) {
TextView tv = new TextView(MainActivity.this);
tv.setText(""+i);
textvs.add(tv);
}
lv.addTouchables(portit); // lv is my listview
You should use ArrayAdapter. You did this the wrong way. Here is a sample:
public class ArrayAdapterDemo extends ListActivity {
String[] items = { "this", "is", "a", "really", "silly", "list" };
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_expandable_list_item_1,
items));
}
I have a ListView with multiple checkboxes (one for each list item). What would be the best way to create an array containing information from the selected checkboxes.
For Example, here's a list.
Item 1 "Ham" Checked
Item 2 "Turkey" NotChecked
Item 3 "Bread" Checked
I would like to create an array containing "ham" and "turkey"
If you used ListView's built-in checkbox method with setChoiceMode() then you only need to call getCheckedItemIds() or getCheckedItemPositions().
public class Example extends Activity implements OnClickListener {
ListView mListView;
String[] array = new String[] {"Ham", "Turkey", "Bread"};
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_checked, array);
mListView = (ListView) findViewById(R.id.list);
mListView.setAdapter(adapter);
mListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(this);
}
public void onClick(View view) {
SparseBooleanArray positions = mListView.getCheckedItemPositions();
int size = positions.size();
for(int index = 0; index < size; index++) {
Log.v("Example", "Checked: " + array[positions.keyAt(index)]);
}
}
}
If the Adapter is bound to a Cursor, then this becomes much more practical.