Is it possible to create a ListView using run()? - android

I would like to know if it is possible to create a list view in runnable using something like this ? Could someone please give me an example to do it? Thank you.
public void testBtnListViewClick(View v) {
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
LinearLayout ll = new LinearLayout(this);
ListView lv = new ListView(this);
String[] values = new String[10];
for(int i=0;i<10;i++){
values[i] = ""+i;
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_item, values);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
Toast.makeText(getBaseContext(), ""+arg2,Toast.LENGTH_SHORT).show();
Log.d("DEBUG", ""+arg2);
}
});
//ll.addView(lv);
ll.addView(lv, LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
setContentView(ll);
}
}

Yes ..you can..runOnUiThread() which runs in the main thread.In android UI changes like Views can be modiied or added only in UI thread..Its in the UI thread so no problem for yours..
inside that this refers to runnable object..so change these lines
LinearLayout ll = new LinearLayout(this);
ListView lv = new ListView(this);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.list_item, values);
into
LinearLayout ll = new LinearLayout(MainActivity.this);
ListView lv = new ListView(MainActivity.this);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this, R.layout.list_item, values);

Related

How to use SimpleCursorAdapter with single_choice and multiple_choice

I am developing a quiz application which contain both multiple answer type and single answer type.the question and answer are store in sqlite database.i use simple cursor adapter and get idea about how to use from here! My question is that how i can switch from simple_list_item_single_choice to simple_list_item_multiple_choice if my answer type changes(single to multiple) and also how can i save the answer choosen.Please give some idea about it.Here is the coding....
db = new DBAdapter(this);
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_1,
db.getAllTitles(),
new String[] { "title" },
new int[] { android.R.id.text1 });
ListView listView = (ListView) findViewById(R.id.list);
listView.setAdapter(adapter);
check this code: for single choice:
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
android.R.layout.simple_list_item_single_choice,
db.getAllTitles(),
new String[] { "title" },
new int[] { android.R.id.text1 });
ListView listView = (ListView) findViewById(R.id.list);
listView.setAdapter(adapter);
listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
for multiple:
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this,
simple_list_item_multiple_choice,
db.getAllTitles(),
new String[] { "title" },
new int[] { android.R.id.text1 });
ListView listView = (ListView) findViewById(R.id.list);
listView.setAdapter(adapter);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
depend on your requirement you have to set one of above: i think you aleady kno which question require single ans & which require multiple depend on that you have to also create list item click like
listView.setOnItemClickListener(new OnItemClickListener() {
private String my_sel_items;
public void onItemClick(AdapterView arg0, View arg1, int arg2,
long arg3) {
if(ans == multiple){
my_sel_items = new String("Selected Items");
SparseBooleanArray a = lView.getCheckedItemPositions();
for (int i = 0; i < a.size(); i++) {
if (a.valueAt(i)) {
my_sel_items = my_sel_items + ","
+ (String) listView.getAdapter().getItem(i);
}
}
Log.v("values", my_sel_items);
}else{
// for single it default selected item
}
}
});

Updating listview in Android

I've made a listview for some games, and when a game is deleted i'd like it to vanish in the listview. I'm trying to use adapter.notifyDataSetChanged(), but i can't get it to work, can you help me?
public static final String MY_SETTINGS = "MySettings";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
DBHelpeR entry = new DBHelpeR(Loadmenu.this);
entry.open();
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.list_item,entry.getGameNames());
setListAdapter(adapter);
entry.close();
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setBackgroundResource(R.drawable.background);
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
lv.setOnItemLongClickListener(new OnItemLongClickListener(){
public boolean onItemLongClick(AdapterView<?> parent, final View view,
int position, long id) {
String gamename = ((TextView) view).getText().toString();
builder.setTitle("Slet " + gamename + "?");
builder.setItems(new CharSequence[]{"Slet"} , new DialogInterface.OnClickListener() {
// Click listener
public void onClick(DialogInterface dialog, int item) {
DBHelpeR entry = new DBHelpeR(Loadmenu.this);
entry.open();
int game_id = entry.getGameID(((TextView) view).getText().toString());
Log.d("load",Integer.toString(game_id));
entry.deleteGame(game_id);
entry.close();
adapter.notifyDataSetChanged();
}
});
builder.show();
return true;
}
});
}
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.list_item,entry.getGameNames());
replace the above line with below :::
ArrayList<String> entries = entry.getGameNames();
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.list_item,entries);
and when you delete just dcall the below two lines again::
entries = entry.getGameNames();
adapter.notifyDataSetChanged();
Updated::
Again before calling adapter.notifyDataSetChanged(); call the below lines::
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.list_item, entry.getGameNames());
setListAdapter(adapter);
call
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,R.layout.list_item,entry.getGameNames());
setListAdapter(adapter);
Again before calling
adapter.notifyDataSetChanged();
Note: make sure you have changed the array for the change to be visible.

on button click reload adapter

I want to change data on listview runtime after button click...
here is my code
oncreate works fine
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Find the ListView resource.
mainListView = (ListView) findViewById( R.id.mainListView );
// When item is tapped, toggle checked properties of CheckBox and Planet.
mainListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick( AdapterView<?> parent, View item,
int position, long id) {
Planet planet = listAdapter.getItem( position );
planet.toggleChecked();
PlanetViewHolder viewHolder = (PlanetViewHolder) item.getTag();
viewHolder.getCheckBox().setChecked( planet.isChecked() );
}
});
// Create and populate planets.
planets = (Planet[]) getLastNonConfigurationInstance() ;
if ( planets == null ) {
planets = new Planet[] {
new Planet("Mercury"), new Planet("Venus"), new Planet("Earth"),
new Planet("Mars"), new Planet("Jupiter"), new Planet("Saturn"),
new Planet("Uranus"), new Planet("Neptune"), new Planet("Ceres"),
new Planet("Pluto"), new Planet("Haumea"), new Planet("Makemake"),
new Planet("Eris")
};
}
ArrayList<Planet> planetList = new ArrayList<Planet>();
planetList.addAll( Arrays.asList(planets) );
// Set our custom array adapter as the ListView's adapter.
listAdapter = new PlanetArrayAdapter(this, planetList);
mainListView.setAdapter( listAdapter );}
but when i want to change it runtime after button click like this i get error ...
private View.OnClickListener onLigyVyber = new View.OnClickListener() {
public void onClick(View button3) {
// Create and populate planets.
planets = (Planet[]) getLastNonConfigurationInstance() ;
planets = new Planet[] {
new Planet("a"), new Planet("b"), new Planet("c"),
new Planet("d")
};
ArrayList<Planet> planetList = new ArrayList<Planet>();
planetList.addAll( Arrays.asList(planets) );
// Set our custom array adapter as the ListView's adapter.
listAdapter = new PlanetArrayAdapter(this, planetList);
mainListView.setAdapter( listAdapter );
i got error on this line
The constructor Ventana.PlanetArrayAdapter(new View.OnClickListener(){}, ArrayList) is undefined
listAdapter = new PlanetArrayAdapter(this, planetList);
Thanks a lot.
use :
listAdapter = new PlanetArrayAdapter(getBaseContext(), planetList);
or you can use YOUR_Activity_NAME.this

Create ListView programmatically

Hi I am new in Android. Could anyone tell me pls whats the wrong with the following code:
public class ListApp extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView lText = new TextView(this);
lText.setId(0);
ListView lView = new ListView(this);
String[] lStr = new String[]{"AA","BB", "CC"};
ArrayAdapter lAdap = new ArrayAdapter(this,lText.getId(),lStr);
lView.setAdapter(lAdap);
lView.setFocusableInTouchMode(true);
setContentView(lView);
}
}
here's a solution that does not require you to write any xml layouts. it uses standard android layouts where possible and no inflation is necessary:
Dialog dialog = new Dialog(this);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Select Color Mode");
ListView modeList = new ListView(this);
String[] stringArray = new String[] { "Bright Mode", "Normal Mode" };
ArrayAdapter<String> modeAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, stringArray);
modeList.setAdapter(modeAdapter);
builder.setView(modeList);
dialog = builder.create();
Try this..
Paste the following code in list_item.xml.
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:textSize="16sp" android:textColor="#ffffff" android:textStyle="bold" android:background="#drawable/border_cell">
</TextView>
Here is the activity class....
public class UsersListActivity extends ListActivity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] statesList = {"listItem 1", "listItem 2", "listItem 3"};
setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item,
statesList));
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getApplicationContext(),
"You selected : "+((TextView) view).getText(), Toast.LENGTH_SHORT).show();
}
});
}
}
Best practice is to separate view (xml layout) and controller (Activity).
If you dont want this, try to put
setContentView(lView);
at the beginning of onCreate
public class ListApp extends ListActivity
Make a layout XML file with your listview and use findViewById to set it's adapter after first setting the content view to your layout

Remove ListView items in Android

Can somebody please give me an example code of removing all ListView items and replacing with new items?
I tried replacing the adapter items without success. My code is
populateList(){
results //populated arraylist with strings
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, results);
listview.setAdapter(adapter);
adapter.notifyDataSetChanged();
listview.setOnItemClickListener(this);
}
// now populating list again
repopulateList(){
results1 //populated arraylist with strings
ArrayAdapter<String> adapter1 = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, results1);
listview.setAdapter(adapter1);
adapter1.notifyDataSetChanged();
listview.setOnItemClickListener(this);
}
Here repopulateList() method will add to ListView items, but it doesn't remove/replace all ListView items.
You will want to remove() the item from your adapter object and then just run the notifyDatasetChanged() on the Adapter, any ListViews will (should) recycle and update on it's own.
Here's a brief activity example with AlertDialogs:
adapter = new MyListAdapter(this);
lv = (ListView) findViewById(android.R.id.list);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
AlertDialog.Builder adb=new AlertDialog.Builder(MyActivity.this);
adb.setTitle("Delete?");
adb.setMessage("Are you sure you want to delete " + position);
final int positionToRemove = position;
adb.setNegativeButton("Cancel", null);
adb.setPositiveButton("Ok", new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
MyDataObject.remove(positionToRemove);
adapter.notifyDataSetChanged();
}});
adb.show();
}
});
I think if u add the following code, it will work
listview.invalidateViews();
To remove an item, Just remove that item from the arraylist that we passed to the adapter and do listview.invalidateViews();
This will refresh the listview
You can use
adapter.clear()
that will remove all item of your first adapter then you could either set another adapter or reuse the adapter and add the items to the old adapter. If you use
adapter.add()
to add data to your list you don't need to call notifyDataSetChanged
int count = adapter.getCount();
for (int i = 0; i < count; i++) {
adapter.remove(adapter.getItem(i));
}
then call notifyDataSetChanged();
Remove it from the adapter and then notify the arrayadapter that data set has changed.
m_adapter.remove(o);
m_adapter.notifyDataSetChanged();
names = db.getSites();
la = new ArrayAdapter<String>(EditSiteList.this,
android.R.layout.simple_list_item_1, names);
EditSiteList.this.setListAdapter(la);
listview.invalidateViews();
this code works fine for me.
You should use only one adapter binded with the list of data you need to list
When you need to remove and replace all items, you have to clear all items from data-list using "list.clear()" and then add new data using "list.addAll(List)"
here an example:
List<String> myList = new ArrayList<String>();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, myList);
listview.setAdapter(adapter);
listview.setOnItemClickListener(this);
populateList(){
List<String> result = getDataMethods();
myList.addAll(result);
adapter.notifyDataSetChanged();
}
repopulateList(){
List<String> result = getDataMethods();
myList.clear();
myList.addAll(result);
adapter.notifyDataSetChanged();
}
Try this code, it works for me.
public class Third extends ListActivity {
private ArrayAdapter<String> adapter;
private List<String> liste;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_third);
String[] values = new String[] { "Android", "iPhone", "WindowsMobile",
"Blackberry", "WebOS", "Ubuntu", "Windows7", "Max OS X",
"Linux", "OS/2" };
liste = new ArrayList<String>();
Collections.addAll(liste, values);
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, liste);
setListAdapter(adapter);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
liste.remove(position);
adapter.notifyDataSetChanged();
}
}
At first you should remove the item from your list. Later you may empty your adapter and refill it with new list.
private void add(final List<Track> trackList) {
MyAdapter bindingData = new MyAdapter(MyActivity.this, trackList);
list = (ListView) findViewById(R.id.my_list); // TODO
list.setAdapter(bindingData);
// Click event for single list row
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
final int position, long id) {
// ShowPlacePref(places, position);
AlertDialog.Builder showPlace = new AlertDialog.Builder(
Favoriler.this);
showPlace.setMessage("Remove from list?");
showPlace.setPositiveButton("DELETE", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
trackList.remove(position); //FIRST OF ALL REMOVE ITEM FROM LIST
list.setAdapter(null); // THEN EMPTY YOUR ADAPTER
add(trackList); // AT LAST REFILL YOUR LISTVIEW (Recursively)
}
});
showPlace.setNegativeButton("CANCEL", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
showPlace.show();
}
});
}
It's simple .First you should clear your collection and after clear list like this code :
yourCollection.clear();
setListAdapter(null);
You can also use listView.setOnItemLongClickListener to delete selected item.
Below is the code.
// listView = name of your ListView
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int
position, long id) {
// it will get the position of selected item from the ListView
final int selected_item = position;
new AlertDialog.Builder(MainActivity.this).
setIcon(android.R.drawable.ic_delete)
.setTitle("Are you sure...")
.setMessage("Do you want to delete the selected item..?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which)
{
list.remove(selected_item);
arrayAdapter.notifyDataSetChanged();
}
})
.setNegativeButton("No" , null).show();
return true;
}
});
//try this:
String text = ( (TextView) view).getText().toString();
adapter.remove(text);

Categories

Resources