Dynamically adding items to listview - android

I am making an android application that needs to use a ListView. Once a user presses a menubutton, it pops up a popupwindow containing a TextView, EditText and two Buttons, "Ok" and "Cancel". Once the user presses "Ok", the text inside the EditText should be added to the ListView. And the cancel Button is obvious. I also want to be able to long press on a ListView item to open a popupwindow containing a delete Button. How can I make this possible? I am using this code so far:
public class NotesActivity extends ListActivity {
/** Called when the activity is first created. */
Button AddItemToListView;
static final String[] COUNTRIES = new String[] {
"Matte på A1 med Ole", "Engelsk på klasserommet", "Film på A1 etter friminuttet"
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.notes);
setListAdapter((ListAdapter) new ArrayAdapter<String>(this, R.layout.list_item, COUNTRIES));
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(), "Note: " + ((TextView) view).getText(),
Toast.LENGTH_SHORT).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu meny) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.listviewmenubuttons, meny);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.AddItemToListView:
Toast.makeText(NotesActivity.this,
"Add note button pressed", Toast.LENGTH_SHORT)
.show();
break;
}
return true;
}
}

Try doing some research on dialogs if you want to add feature after accessing listview.setonlongclick(). Here is a link on android dialog developers.

Since you are using an ArrayAdapter, when the user taps on add, you must add the new item to your array (change from an array to an List to make it easier). Then you should call notifyDataSetChanged() from the ArrayAdapter.
For deleting is the same, but you remove the item from the List. The call to notifyDataSetChanged() is to tell the ListView that it needs to redraw itself.

Related

How to Open a Custom Spinner Item from MainActivity?

I have two activities viz., Activity A and B and I have a spinner in Activity B with 5 options(like country names). On clicking an item, a toast is shown to the user.
//Performing action onItemSelected
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int position,long id) {
Toast.makeText(getApplicationContext(),country[position] ,Toast.LENGTH_LONG).show();
}
In my Activity A, I use a button to open Activity B using Intent. The activity B is opened with the first item of the spinner.
Question
Is there a way so that on clicking the button in Activity A, second spinner item is opened and the respective toast is shown?
you can use the setSelection(int item) method of your spinner (see: https://developer.android.com/reference/android/widget/AbsSpinner.html#setSelection(int)).
For example:
//Activity B
#Override
public void onCreate(Bundle savedInstanceState)
{
//find spinner
spinner.setSelection(1)
}
This answer is based on the assumption that you want to set 2nd item of the array as the default selection.
Use the following code:
final Spinner spinner = (Spinner) view.findViewById(R.id.spinner1);
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<>(
getActivity(), android.R.layout.simple_spinner_dropdown_item,
getResources().getStringArray(R.array.names));
spinner.setAdapter(arrayAdapter);
spinner.post(new Runnable() {
#Override
public void run() {
spinner.setSelection(1);
}
});
I am late now I think...

Android spinners dynamic data binding

I am new to android , I have an activity with 3 multiple spinners as bellow
Spinner 1:department
Spinner2:semester
Spinner3:subjects
and one button
spinner1 shows the department on select of department it has to display the semester on select of semester it has to display the subject spinner
NOTE:-SUBJECT SPINNER DEPENDS ON THE SELECTION OF SEMESTER SPINNER AS WELL AS DEPARTMENT SPINNER.
something like country, state, city spinners but suggest me some other ideas to do it because i am using string resources to list the items of spinners
Please help me
Try something like this in your activity.
Firstly, make your activity implement AdapterView.OnItemSelectedListener & View.OnClickListener.
private Spinner mDepartmentSpinner;
private Spinner mSemesterSpinner;
private Spinner mSubjectSpinner;
private Button mButton;
// Values to fill first spinner with.
private String[] mDepartments = {
"Department 1",
"Department 2",
"Department 3",
"Department 4",
};
private String[] mSemesters;
private String[] mSubjects;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
}
private void initViews() {
// Find the spinners and button, declared in the activity's resource file
mDepartmentSpinner = (Spinner) findViewById(R.id.department_spinner);
mSemesterSpinner = (Spinner) findViewById(R.id.semester_spinner);
mSubjectSpinner = (Spinner) findViewById(R.id.subject_spinner);
mButton = (Button) findViewById(R.id.button);
// Initialise spinner with values, placing them into a textview
mDepartmentSpinner.setAdapter(new ArrayAdapter<String>(getContext(), R.layout.text_view, mDepartments));
// Attach a listener for item selection
departmentSpinner.setOnItemSelectedListener(this);
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// Work out which spinner was selected
switch (view.getId()) {
case R.id.department_spinner:
// Get the selected item
String selectedDepartment = mDepartments[position];
// Get values to fill the semester spinner with, based on initial selection.
mSemesters = getSemestersFor(selectedDepartment);
// Initialise spinner with values, placing them into a textview
mSemesterSpinner.setAdapter(new ArrayAdapter<String>(getContext(), R.layout.text_view, mSemesters));
// Attach a listener for item selection
mSemesterSpinner.setOnItemSelectedListener(this);
break;
case R.id.semester_spinner:
// Get the selected item
String selectedSemester = mSemesters[position];
// Get values to fill the subject spinner with, based on second spinner selection.
mSubjects = getSubjectsFor(selectedSemester);
// Initialise spinner with values, placing them into a textview
mSubjectSpinner.setAdapter(new ArrayAdapter<String>(getContext(), R.layout.text_view, subjects));
// Attach a listener for item selection
mSubjectSpinner.setOnItemSelectedListener(this);
break;
case R.id.subject_spinner:
mButton.setOnClickListener(this);
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Please select an option from each spinner.", Toast.LENGTH_LONG).show();
}
});
}
#Override
public void onClick(View v) {
// Go to your new activity, passing the selected subject
Intent intent = new Intent(this, SubjectActivity.class);
intent.putExtra("KEY_SUBJECT", (String) mSubjectSpinner.getSelectedItem());
startActivity(intent);
}
You can get the selected subject in the SubjectActivity like so...
#Override
public void onCreate(Bundle savedInstanceState) {
if (getIntent().getExtras().containsKey("KEY_SUBJECT") {
String subject = getIntent().getExtras().getString("KEY_SUBJECT");
}
}
Code for R.layout.text_view
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
You will need to implement the following methods yourself, I don't know your logic!
private String[] getSemestersFor(String department) {
// your code here
}
private String[] getSubjectsFor(String semester) {
// your code here
}

Android onItemLongClick adds position to the arrayList in different activity

I have got two activities.
My goal is: After longClick on any ListView position in activity 2, I want some String to be added to ListView in activity 1. From activity 2 I'm going back to activity 1 by pressing back button. Each ListView has got different adapter.
I tried with Bundle (put extra), but it makes app crash.
Fragment of code from activity 1:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.start_layout);
mDrawerList = (ListView)findViewById(R.id.navList);
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
mActivityTitle = getTitle().toString();
addDrawerItems();
setupDrawer();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
private void addDrawerItems() { //It adds text ect. to listView - It works so I cut out the rest of code
ar.add("anything");
ar.add(lv.try);
mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, ar);
mDrawerList.setAdapter(mAdapter);
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
});
}
Simply adding like ar.add("anything"); works. The lv.try contains by default text "First text". I tried to update this variable in activity 2 onItemLongClick fragment of code:
mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
//What to type here?
return false;
}
});
Putting simply try = "Second text"; will not update my try variable. I tried also with Bundle (extras) but without success. Any ideas?
I don't know if I understood the question. Anyway, have you tried to override onBackPressed?
In the second activity you create a boolean variabile and inizialize it as false, then change its value when you perform a long click:
mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
longClick = true;
return false;
}
});
Remember, longClick has to be a class variable!
Outside onCreate:
#Override
public void onBackPressed() {
Intent intent = new Intent(SecondActivityName.this, FirstActivity.class);
intent.putExtra("longClick", longClick);
finish();
startActivity(setIntent);
}
And in the first Activity:
Intent intent = getIntent();
if (intent.getBooleanExtra("longClick", false)) {
addDrawerItems();
}
What does add position mean ?
In my opinion add position means add one element to a structure (array, list, etc).
So basically what I mean is that you can have an array in your CustomApplicatioClass or even a Static array(someone probably would not agree with me) and onItemLongClick() add the element you want in the structure.
Then when you load the Activity with the ListView you can do your ListView stuff using the updated structure
hope it helps

Android Spinner - onItemSelected / setOnItemSelectedListener not triggering

This is driving me nuts since it's something I've done before but can't figure out why it isn't working now...
I've got a menu button, implemented in the usual way via a menu.xml file and the onOptionsItemSelected method with a switch in it, that creates and displays a spinner.
I've added the setOnItemSelectedListener, but it never seems to trigger. The spinner appears, I pick an option or back out, neither onItemSelected or onNothingSelected are called.
Here is all the code between the "case" and "return true" of the menu-button-handling switch statement. (topThis is a variable referring to the context of the activity - works fine for all other toasts in the app)
String[] widgetModes = {"Mode 1", "Mode2"};
ArrayAdapter<String> widgetModeAdapter = new ArrayAdapter<String> (this, android.R.layout.simple_spinner_item, widgetModes);
widgetModeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Spinner widgetModeSpinner = new Spinner(this);
widgetModeSpinner.setAdapter(widgetModeAdapter);
widgetModeSpinner.setPrompt("Choose Widget Mode");
widgetModeSpinner.setOnItemSelectedListener(new OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id)
{
Toast.makeText(topThis, "derp", Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parentView)
{
Toast.makeText(topThis, "herf", Toast.LENGTH_LONG).show();
}
});
widgetModeSpinner.performClick();
Any ideas? I vaguely suspect that the fact I'm creating the Spinner programmatically is the problem...
I had the similar problem when I was implementing a spinner, I resolved it by getting the parent View and set Adapter-
spinner1 =(Spinner)findViewById(R.id.spinner1);
spinner1.setAdapter(BindSpinner("ProgramMaster",cols,null,true,""));
spinner1.setOnItemSelectedListener(new OnItemSelectedListener()
{
protected Adapter initializedAdapter=null;
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id)
{
if(initializedAdapter !=parentView.getAdapter() ) {
initializedAdapter = parentView.getAdapter();
return;
}
String selected = parentView.getItemAtPosition(position).toString();
if(abc.equals("Select") && !selected.equals("Select"))
{
do something
}
else
{
Do something
}
textQualification=selected;
SearchUpdated("Qualification");
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// your code here
}
});
Remember that you can't re-select the same spinner item, it always sets the first item as selected if you are not adding some custom code to handle the spinner selection.
For the Toast not showing, I would suggest to always use the "MyActivity.this" as your context when creating a Toast inside a listener interface like this:
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
/**
* Called when a new item is selected (in the Spinner)
*/
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// An spinnerItem was selected. You can retrieve the selected item using
// parent.getItemAtPosition(pos)
Toast.makeText(MyActivity.this, "Hello Toast",Toast.LENGTH_SHORT).show();
}
public void onNothingSelected(AdapterView<?> parent) {
// Do nothing, just another required interface callback
}
}); // (optional)
And the .show() at the end is easy to forget sometimes;)
Actually, if your spinner visibility is set to gone then it will trigger the click of it when you call performclick() method but it will not trigger its setOnItemSelectedListener
so you need to change the visibility then it will work
I know the question is a bit old, but in case you are waiting for a AsyncTask callback, make sure that you let your adapter know of the data changes by calling notifyDataSetChanged() on the callback thread!
#Override
public void onPostExecute(String result) {
///do something with your data
spinnerArrayAdapter.notifyDataSetChanged();
}

Android custom listview, setOnItemSelectedListener not working

I'm just beginning Android development, and I'm working to get a Custom listview with a checkbox working. I've created a base class that extends Activity, Created an Adapter and overrode the getView() method to add the checkbox to the listview. I'm assuming I need to do this because I need something equivalent to didSelectRowIndexAtPath from Obj C to update my model. Please let me know if there's an alternate way of doing this too!
Now in my base class, I have the following code -
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout);
setContentView(R.layout.facilityscreen);
/* Static Data source */
facilityModel = new FacilityDataModel[2];
facilityModel[0] = new FacilityDataModel();
facilityModel[1] = new FacilityDataModel();
facilityModel[0].setFacilityName("Test 1");
facilityModel[0].setFacilityID("Facid0001");
facilityModel[0].setChecked(false);
facilityModel[1].setFacilityName("Test 2");
facilityModel[1].setFacilityID("Facid0002");
facilityModel[1].setChecked(true);
facilityListView = (ListView) findViewById(R.id.facilityListView);
FacilityScreenAdapter adapter = new FacilityScreenAdapter(this, facilityModel);
facilityListView.setAdapter(adapter);
myPatBtn = (Button) findViewById(R.id.myPatBtn);
myPatBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
int i=0;
i++;
}});
facilityListView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
int i=0;
i++;
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
My problem now is the setOnItemSelectedListener isn't getting called at all. Been struggling with this for a couple of hours now, and I can't figure out why it wouldn't get called at all.
Any help is much appreciated!
Thanks,
Teja.
I know this is an outdated answer but I'm going to write it just in case some other fellow who has the same "problem" bumps onto this page :
The solution to the above problem which is not a problem but just a misunderstanding is that the ListView.onItemSelected() event is fired up, upon :
1) Navigating through the emulators-cross handles or
2) as far-as my HTC-Hero is concerned, the rolling-action on the white little roller-ball.
You don't have to extend your activity explicitly to a ListActivity.
Here's my tiny little code which retrieves a phone number from
a TextView control, inside a listview item.
When the user either touches the list item or scrolls through the list with
the little roller-ball the below Events, fire up and MakeACall() method is called :
myList.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view, int position, long i)
{
TextView myPhone = (TextView)view.findViewById(R.id.txtphone);
MakeACall(myPhone.getText().toString());
}
});
myList.setOnItemSelectedListener(new OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> parent, View view, int position, long i)
{
TextView myPhone = (TextView)view.findViewById(R.id.txtphone);
MakeACall(myPhone.getText().toString());
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
I hope that was helpful... :)
There exists already the possibility to have a ListView with checkboxes.
public class List11 extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice, GENRES));
final ListView listView = getListView();
listView.setItemsCanFocus(false);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
}
private static final String[] GENRES = new String[] {
"Action", "Adventure", "Animation", "Children", "Comedy", "Documentary", "Drama",
"Foreign", "History", "Independent", "Romance", "Sci-Fi", "Television", "Thriller"
};
}
I've taken this from the APIDemos 'cause it was the simplest. You can then get the selected items by using:
long[] selectedIds = getListView().getCheckItemIds();
What you may also be interested in is the CheckedTextView which is used internally in the list.
To the part of the onListItemClick problem
Try to extend from ListActivity rather than Activity. Then override the onListItemClick. That should work.
use
setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
// here you code
}
})
instead of setOnItemSelectedListener
As setOnItemSelectedListener is called when item is being selected not clicked so to get clicked item you must use setOnItemClickListener this will work
You should set all focusable items in custom list layout to false:
android:focusable="false"
also I think you should not use attributes like android:clickable="true" for them.
The lack of the item selected listener getting called is by design and is based on which mode the device is in. In touch mode, there is no focus and no selection. Your UI should use widgets that differentiate between touch for selection versus touch for scrolling. Radio buttons, for example, are good when there is a single selection choice.

Categories

Resources