I'm using a ListActivity on wich I get the Access Points in the WIFI range, and list them in a cheking list.
I've been successfull doing this, but I would like to get the cheked items when I click in the footer button. How do I get them to a String array??
This is the code:
public class APselection extends ListActivity {
protected static final String TAG = "teste";
/** Called when the activity is first created. */
private TextView mScanList;
public List<ScanResult> listaAPs;
protected WifiManager wifiManager;
private IntentFilter mWifiStateFilter;
public String SCAN;
public String[] SCANed;
public String scanAP;
public ListView lv;
public ListView lv1;
public List<Long> list = new ArrayList();
public String[] checked;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
View footer = View.inflate(this, R.layout.footer, null);
wifiManager= (WifiManager)getSystemService(Context.WIFI_SERVICE);
int i;
//function to get the APs
SCANed=handleScanResultsAvailable().split("SPl");
lv=getListView();
lv.addFooterView(footer);
setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, SCANed));
lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
lv.setTextFilterEnabled(false);
}
}
There are several ways to do this. The easiest is probably to implement the OnClickListener for the ListView. When the user clicks a list item, extract the String from the clicked item. Store the items in an ArrayList. When the user clicks, if the list contains the String, remove it, otherwise add it. Bam. List of all selected items.
I don't think there is a way to directly get the checked item to a String array from the ListView, you have to go through intermediate steps :
You can use ListView.getCheckedItemIds to get an array of the id of the checked items. These id are assigned by your list adapter. Since you're using an ArrayAdapter, position=id, so you can just use ArrayAdapter.getItem() to get the String associated with each checked item id.
This would look like :
btn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
long ids[] = lv.getCheckedItemIds();
String checkedItems[] = new String[ids.length];
for (int i=0; i<ids.length; i++)
checkedItems[i] = adapter.getItem(i);
//You got your array of checked strings
}
}
Note that this require access to the adapter, so you would have to assign your ArrayAdapter to a variable.
Related
The following code consist of the listview function for displaying data from sqlite.
The issue is that no matter which data i selected on, it will only delete the last data and not the data being selected. How can i go about solving the issue? please help.
Thank you.
Arealist.java
public class Arealist extends AppCompatActivity {
public static ListView listView;
public static ArrayList<Area> list;
AreaListAdapter adapter = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
listView = (ListView) findViewById(R.id.listView);
list = new ArrayList<>();
adapter = new AreaListAdapter(this, R.layout.area_items, list);
listView.setAdapter(adapter);
//get all data
Cursor cursor = MainActivity.sqLiteHelper.getData("SELECT * FROM AREA");
list.clear();
while (cursor.moveToNext()) {
int id = cursor.getInt(0);
double area = cursor.getDouble(1);
String date = cursor.getString(2);
list.add(new Area(id, area, date));
}
adapter.notifyDataSetChanged();
}
It seems your problem is in this line MainActivity.sqLiteHelper.deleteData(Area.getId());
Try with this
MainActivity.sqLiteHelper.deleteData(area.getId());
Make Area Object local.
set Area Id in delete buttons as a Tag and get it in onClick().
Add In getView()
holder.btnDelete.setTag(area.getId());
Add In OnClick()
final int areaId = view.getTag();
Add in AlertDialog:
MainActivity.sqLiteHelper.deleteData(areaId);
My app implements a HashMap, such that when a key is typed in the AutoCompleteTextView editText, and user clicks a dropdown item, the value gets displayed on a textView.
The only problem is that the clicked drop-down item does not respond on the first click (this only happens once, after the app is launched but works fine subsequently), the user MUST re-type a key and click the item before it displays the value.
Any suggestions as to how to resolve this?
Java code:
public class MainActivity extends ActionBarActivity
{
Map<String, String> map = new HashMap<String, String>();
private EditText autocomplete_searchField;
private TextView displayField;
String note;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
autocomplete_searchField = (AutoCompleteTextView) findViewById(R.id.autocomplete_searchField);
// Gets a reference to the AutoCompleteTextView in the layout
final AutoCompleteTextView textView = (AutoCompleteTextView) findViewById(R.id.autocomplete_searchField);
// Gets the string array
String[] musicNote = getResources().getStringArray(R.array.music_notes_array);
// Creates the adapter and set it to the AutoCompleteTextView
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, musicNote);
textView.setAdapter(adapter);
displayField = (TextView) findViewById(R.id.displayField);
textView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id){
displayField.setText(map.get(adapterView.getItemAtPosition(position).toString()));
String note = autocomplete_searchField.getText().toString();
displayField.setText(map.get(note));
map.put("Doe", "a deer, a female deer");
map.put("Ray", "a drop of golden sun");
}
Most of the related solutions I've seen treat buttons, but not AutoCompleteTextView drop-down items. I've also tried setting focus both in my JAVA and XML but those didn't resolve the issue.
I didn't understand very well what you are trying to do, but looking in your code, I saw a couple of wrong things in it. Perhaps it is the problem. Moreover I added some lines into your code, so the here is it:
public class MainActivity extends ActionBarActivity {
private Map<String, String> map = new HashMap<String, String>();
private AutoCompleteTextView autocomplete_searchField;
private TextView displayField;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
autocomplete_searchField = (AutoCompleteTextView) findViewById(R.id.autocomplete_searchField);
displayField = (TextView) findViewById(R.id.displayField);
// Gets the string array
String[] musicNote = getResources().getStringArray(R.array.music_notes_array);
// Creates the adapter and set it to the AutoCompleteTextView
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, musicNote);
autocomplete_searchField.setAdapter(adapter);
autocomplete_searchField.setThreshold(1);
autocomplete_searchField.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
autocomplete_searchField.showDropDown();
}
});
autocomplete_searchField.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id){
displayField.setText(map.get(adapterView.getItemAtPosition(position).toString()));
}
}
}
}
Test it before do any change in order to realize if the issue was fixed. Then you do whatever you wanna do ;)
Well, this is the setting:
Code for the activity
public class Users_List extends Activity {
private ArrayList<Users> users;
private ListView lvusers;
private int user_selected;
private DB db;
private ListAdapter adaptador;
private static final int NEW_USER = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.users_list);
DB db = new DB(this);
users = db.getAllUsers();
lvusers = (ListView) findViewById(R.id.listview);
adaptador = new AdaptadorUsersList(this, users);
lvusers.setAdapter(adaptador);
lvusers.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
registerForContextMenu(lvusers);
final Button new_user = (Button) findViewById(R.id.btn_new_user);
nuevo_socio.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Users_List.this,
User_Form.class);
startActivityForResult(intent, NEW_USER);
}
});
lvusers.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> a, View view, int position, long id) {
//HERE...LONG ID IS ALWAYS ZERO, WHY???
Log.d("Selected User--------", "---------------------"+id+"--------");
openContextMenu(lvusers);
return true;
}
});
}
//Here the codes continues....
}
I readed that the long id param. on onItemLongClick is actually the id of the row that was clicked right? so, what's wrong here that the id is returning always "0" as value on logcat?
Thank you!
the ID of the onItemClickListener or onItemLongClickListner is the same as the ID of the row if the adapter extends CursorAdapter or simpleCursorAdapter because the Cursor will take care of putting the Item's ID to the Long ID.
Bare in mind that your ID column or the primary key field should have the name of "_id". here is an example of how to implement Custom CursorAdapter.
Edit
You can use BaseAdapter as CursorAdapter since from the source code of CursorAdapter it extends the BaseAdapter however you will use getView() to call the bindView() and newView() where these two functions are the main functions of the CursorAdapter
so basically you are doing the CursorAdapter from the scratch refer to this question where they explain it more in details.
hope this answer your question.
I have an activity with a list fragment in it that has a layout with a checkbox for each row. I set the onclick xml attribute for the checkbox and do the following for testing
public void onBoxClick(View v){
checkedItems = listview.getCheckedItemPositions();
int checkedItemsCount = checkedItems.size();
}
checkedItemsCount comes back 0, I thought to get what items that are checked you use the listview.getCheckedItemPositions() but it is not so how do I know what is checked in the list?
this is my listfragment creation
#Override
public void onActivityCreated(Bundle state){
super.onActivityCreated(state);
listview = getListView();
listview.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listview.setItemsCanFocus(false);
setEmptyText("No Bowlers");
registerForContextMenu(getListView());
populateList();
}
This post might help. It gives a solution using a custom ResourceCursorAdapter, which provides a CheckBox and a TextView for each ListView row.
To select multiple items in ListView, check this page. Note that the example uses a ListActivity instead of a ListFragment, but your code will end up being extremely similar. Just make sure you implement the Fragment lifecycle methods correctly (i.e. setting the Adapter in the ListFragment's onActivityCreated(), etc.).
I got around the problem by Custom Adapter's bindView, I created an ArrayList<Integer> variable
ArrayList<Integer> mCheckedItems = new ArrayList<Integer>();
and In the bindView I set a checkedchangelistener on the checkbox to see if the box was checked or not. If it was checked I put the id from the database that the cursor got into the mCheckedItems Array
adapter:
public class CheckAdapter extends SimpleCursorAdapter{
Context context;
public CheckAdapter(Context context, int layout, Cursor c,String[] from, int[] to,int flag) {
super(context, layout, c, from, to);
this.context = context;
}
#Override
public void bindView(View view,Context context,Cursor cursor){
final String name = cursor.getString(cursor.getColumnIndex(BowlersDB.NAME));
final int id = cursor.getInt(cursor.getColumnIndex(BowlersDB.ID));
TextView tv = (TextView)view.findViewById(R.id.nameCheckTV);
tv.setText(name);
CheckBox cb = (CheckBox)view.findViewById(R.id.checkBox1);
cb.setOnCheckedChangeListener(new OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
if(isChecked){
mCheckedItems.add(id);
}else if(!isChecked){
for(int i=0; i< mCheckedItems.size(); i++){
if(mCheckedItems.get(i) == id){
mCheckedItems.remove(i);
}
}
}
}
});
}
After the id was inserted into the array I used the array list to used them how I needed
I have two string arrays, here s1[] contains a list of names and s2[] contains URL's associated with the respective name, now i need to populate ListView, with the names and on clicking any of the names, i want to start an intent for the browser to handle the URL.
How do i do that?
Use an array adapter to populate the listview from s1, and in the click handler for the listview find the URL for the given list position, and fire off an intent to the browser.
For an example of using an array adapter see the API demos and in particular list1.
For an example of setting an activity as an onItemClickListener see https://github.com/nikclayton/android-squeezer/blob/cache-server-data/src/com/danga/squeezer/AlbumsListActivity.java#L88 and https://github.com/nikclayton/android-squeezer/blob/cache-server-data/src/com/danga/squeezer/AlbumsListActivity.java#L288.
Create a class like:
class Link{
public String name;
public String link;
}
You can then create a custom listview which extends 'ArrayAdapter' and override 'getView' as well as 'onItemSelected'. In both of these method you will be able to get the item using the 'position' parameter.
public class MyActivity extends ListActivity{
private ArrayList<String> urls = new ArrayList<String>();
private ArrayList<String> names = new ArrayList<String>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
urls.add("http://www.google.com");
names.add("google");
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, android.R.id.text1, names);
setListAdapter(adapter);
}
protected void onListItemClick (ListView l, View v, int position, long id){
String url = urls.get(position);
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
}