How to add ListView items on button click using adapter - android

How to take data that was typed in EditText and by clicking "submit" in that window should add it to previous activity listview items?
What I need to do is:
Creating EditText and submit button
Creating listview in same Activity
By clicking submit button it should display it in listview.
I saw this similar question here:add items to listview dynamically android
But i couldn't understand the answer.Somebody please explain how to do this.

You just do the following :
Prepare your xml like this :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<EditText
android:id="#+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_toLeftOf="#+id/addItem"
android:hint="Add a new item to List View" />
<Button
android:id="#+id/addItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:text="Add" />
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/editText" >
</ListView>
</RelativeLayout>
Activity looks like following :
public class MainActivity extends Activity {
EditText editText;
Button addButton;
ListView listView;
ArrayList<String> listItems;
ArrayAdapter<String> adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.editText);
addButton = (Button) findViewById(R.id.addItem);
listView = (ListView) findViewById(R.id.listView);
listItems = new ArrayList<String>();
listItems.add("First Item - added on Activity Create");
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, listItems);
listView.setAdapter(adapter);
addButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
listItems.add(editText.getText().toString());
adapter.notifyDataSetChanged();
}
});
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position,
long id) {
Toast.makeText(MainActivity.this, "Clicked", Toast.LENGTH_LONG)
.show();
}
});
}
}

Create String Arraylist and initialize it
ArrayList<String> str1 = new ArrayList<String>();
Add some values on it
str1.add("First Row");
str1.add("Second Row");
str1.add("Third Row");
str1.add("Fourth Row");
str1.add("Fifth Row");
Then set Adapter to ListView
adapter=new ListAdapter(this,str1);
list.setAdapter(adapter);
then add your EditText text into str1 and then called adapter.notifyDataSetChanged(); like
str1.add(edit_message.getText().toString());
adapter.notifyDataSetChanged();
Try to add this code into Button onclick()
Demo Output:

Suppose you have an arraylist
ArrayList<String> dataList = new Arraylist ();
So On clicking of button, you need to add the new data item into your data arraylist.
For this first take the value entered in edittext and store in a string.
String editedValue = yourEditText.getText.toString();
Then we need to add this in our datalist.
Like
dataList.add(editedValue);
And then just call adapter.notifyDataSetChanged()
yourAdapter.notifyDataSetChanged();
It will work.

Related

spinner clicking on EditText

When I click EditText, I want spinner to open the menu. When I click on textviewplaces, I want the spinner menu to be opened. How can I do this?
public class MainActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener, OnItemSelectedListener {
private Spinner spinnerDevice;
private static final String[] paths = {"......"};
TextView textviewPlaces;
spinnerDevice = (Spinner)findViewById(R.id.spinnerDevice);
ArrayAdapter<String>adapterSpinnerDevice = new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_spinner_item,paths);
textviewPlaces = findViewById(R.id.places_textView);
adapterSpinnerDevice.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerDevice.setAdapter(adapterSpinnerLocation);
spinnerDevice.setOnItemSelectedListener(this);
XML File:
<AutoCompleteTextView
android:id="#+id/places_textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="44dp"
android:layout_marginTop="31dp"
android:text="TextView"
android:drawableLeft="#drawable/location"
android:drawablePadding="2dp"
android:ems="10"
android:textStyle="bold" />
Use AutoCompleteTextView instead of it
final ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
getApplicationContext(), android.R.layout.simple_dropdown_item_line,
paths);
//ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String> (this, android.R.layout.select_dialog_item, paths);
final AutoCompleteTextView textView;
textView = (AutoCompleteTextView) findViewById(R.id.textView);
textView.setAdapter(arrayAdapter);
/* textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View arg0) {
textView.showDropDown();
}
}); */
Define UI element in your layout file
<AutoCompleteTextView
android:id="#+id/textView"
android:layout_width="match_content"
android:layout_height="wrap_content"
android:ems="10" />
If you want something like this image
AutoCompeleteTextView Exmaple
Arwy Shelke answer can help you, but if you want to open a real spinner you can use this code:
spinner.performClick();

setOnItemClick isnt getting recognized(Android)

I am displaying a Listview of recorded data and when the user clicks on a specific list item, it triggers an intent and brings the user to the profile for that selected user. I worked when i first ran my project but ever since it just will not work. Thank you in advance.
public class CowListView extends ListActivity {
RegisterCowAdapter cowAdapter;
private DataBaseHelper databaseHelper;
public ListView listView;
TextView student_Id;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.cow_list_item);
cowAdapter = new RegisterCowAdapter(this);
cowAdapter.open();
updateCowUI();
listView = (ListView) findViewById(android.R.id.list);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
student_Id = (TextView) view.findViewById(R.id.cowtagnolist);
String studentId = student_Id.getText().toString();
Intent objIndent = new Intent(getApplicationContext(), CowProfile.class);
Toast.makeText(CowListView.this, "Clicked", Toast.LENGTH_SHORT).show();
objIndent.putExtra("student_Id", Integer.parseInt(studentId));
startActivity(objIndent);
}
});
}
private void updateCowUI() {
Cursor cursor = cowAdapter.getAllCowData();
startManagingCursor(cursor);
String[] from = new String[]{RegisterCowAdapter.COWTAGNO, RegisterCowAdapter.COWDOB};
int[] to = new int[]{R.id.cowtagnolist, R.id.cowdoblist};
SimpleCursorAdapter reminders = new SimpleCursorAdapter(
this,
R.layout.cow_list_item,
cursor,
from,
to
);
this.setListAdapter(reminders);
}
}
private void updateCowUI() {
Cursor cursor =cowAdapter.getAllCowData();
startManagingCursor(cursor);
String[] from = new String[]{RegisterCowAdapter.COWTAGNO, RegisterCowAdapter.COWDOB};
int[] to = new int[]{R.id.cowtagnolist, R.id.cowdoblist};
SimpleCursorAdapter reminders = new SimpleCursorAdapter(
this,
R.layout.cow_list_item,
cursor,
from,
to
);
this.setListAdapter(reminders);
}
}
My XML
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/RelativeLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:longClickable="true">
<ListView
android:id="#android:id/list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
</ListView>
<TextView
android:id="#+id/cowtagnolist"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#color/black"
android:focusableInTouchMode="false"
android:clickable="false"
android:focusable="false"
android:descendantFocusability="blocksDescendants"
>
</TextView>
<TextView
android:id="#+id/cowdoblist"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="17dp"
android:focusableInTouchMode="false"
android:clickable="false"
android:focusable="false"
android:descendantFocusability="blocksDescendants"
android:textColor="#color/black">
</TextView>
</LinearLayout>
Might be one of two things.
You have implemented OnClickListener but you have not set the ListView to listen to that specific class nor have you called any method in your onCreate that will set the ListView's listener to that class.Secondly I think you might need to implement OnItemClickListener and not onCLickListener since thats what is on the ListView, an Item.Im confused though why do you have onClick and then you set the listener inside this method? How will it know in the first place that the view has been clicked if it is not listening from the beginning i.e. in the onCreate or a method called in the onCreate ? Your logic seems abit off

Listview Click doesn't fire

I have a listview, whick get its data from a SQLite db. I would like to let user change value of field by click on items. But with following code, the click event is not fired. Could some one help on it? Thanks!
public class BDXDeviceActivity extends Activity {
private DeviceListControl deviceListControl;
private ListView listViewDevice;
private DeviceListAdapter2 deviceListAdapter2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// using a custom layout, otherwise a system default of List
setContentView(R.layout.activity_device_list);
listViewDevice = (ListView) findViewById(R.id.listViewDevice);
deviceListControl = new DeviceListControl(this);
// setListAdapter(new DeviceListAdapter2(this, deviceListControl.getDevices()));
deviceListAdapter2 = new DeviceListAdapter2(this, deviceListControl.getDevices());
listViewDevice.setAdapter(deviceListAdapter2);
listViewDevice.setClickable(true);
listViewDevice.setOnItemClickListener(onItemClickListener);
}
AdapterView.OnItemClickListener onItemClickListener = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getBaseContext(), "clicked", Toast.LENGTH_SHORT).show();
DeviceName deviceName = (DeviceName) listViewDevice.getAdapter().getItem(position);
deviceListControl.deleteDevice(deviceName.getId());
// after delete, reread the list adapter and get names list via namechange
deviceListAdapter2 = new DeviceListAdapter2(getBaseContext(), deviceListControl.getDevices());
listViewDevice.setAdapter(deviceListAdapter2);
// Display success information
Toast.makeText(getApplicationContext(), "Deleted!", Toast.LENGTH_LONG).show();
}
};
... layout file
<EditText
android:id="#+id/txtSearchDevice"
android:layout_width="200dp"
android:layout_height="30dp"
android:background="#f7f5b1a3"
android:focusable="false"
/>
<Button
android:layout_width="50dp"
android:layout_height="wrap_content"
android:id="#+id/btnSearchDevice"
android:textColor="#ff151515"
android:background="#android:drawable/ic_menu_search"
android:focusable="false"/>
</LinearLayout>
<ListView
android:id="#+id/listViewDevice"
android:layout_width="match_parent"
android:layout_height="300dp">
</ListView>

Adding items to textview and scrollbar stays consistent

I am working on an Android app. In my app there is an activity that it has a ListView. ListView elements changes dynamically (programmatically). But when I add a new element, listview scrolls and I don't want it. I want to adding elements to listview and user see new elements just when user interact with it, not automatically. I call notifyDataSetChanged() on listview adapter.
I have an example to clear my mean:
ListView contains = **{ 1 , 2 , 3 , 4 , 5}
But screen size just allow 3 of them. Suppose now {3, 4, 5} are in screen.
Now, we add the '6' element and listview automatically scrolls to top and screen shows {4 , 5 , 6}
I want to when I add the '6' element, listview don't scrolls and shows the same things (to be consistent) and if user interact with listview and scroll, he see '6' element.
Just call listView.setSelectionAfterHeaderView(); after updating the list
I am new to android too.
I tried adding elements to listview on button click, i didnt face those problems....
<RelativeLayout
...>
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginTop="133dp">
</ListView>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="55dp"
android:text="Button" />
public class MainActivity extends Activity {
ListView lv;
Button btn;
int counter = 0;
ArrayAdapter<String> adapter;
ArrayList<String> array = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.listView1);
btn = (Button) findViewById(R.id.button1);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, array);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String s = "Clicked "+ ++counter;
array.add(s);
adapter.notifyDataSetChanged();
}
});
lv.setAdapter(adapter);
}
}
It doesn't auto scroll to the bottom.
But if you add
android:stackFromBottom="true"
android:transcriptMode="alwaysScroll"
to the listview xml then it auto scroll to the bottom when you add a new element to the listview.
I hope it helps.

switching from a CustomAdapter ListView to an standard ArrayAdapter ListView fails

I recently got interested in Android coding and working my way through several tutorials. however, right now i m stuck for a day and hope you guys can help me out.
basically i want to create a main menu and a submenu for every main menue entry. (right now this is only the case for the first entry)
For the main menu I used a ListView with different icons (realized with a custom adapter). Selecting one of the menu entries works fine in general, but if I choose to configure the onitemclick to start a new activity which is another (simple) ListView which uses the ArrayAdapter it breaks after switching into the submenu activity.
Strangely if i use the ArrayAdapter in both ListViews it is no problem; also when using CustomAdapter in both.
Here is the code, thanks in advance for any help ;)
main menu:
public class MainActivity extends ListActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// storing string resources into Array contentmenu
String[] contentmenu = getResources().getStringArray(R.array.mainmenu_cats);
// storing icons in Array
TypedArray iconarray = getResources().obtainTypedArray(R.array.mainmenu_icons);
// Binding resources Array to ListAdapter
this.setListAdapter(new ImageAndTextAdapter(this, R.layout.list_item, contentmenu, iconarray));
ListView lv = getListView();
// listening to single list item on click
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// Launching new Activity on selecting single List Item
switch( position )
{
case 0: Intent newActivity0 = new Intent(getApplicationContext(),SubActivity.class);
startActivity(newActivity0);
break;
case 1: Intent newActivity1 = new Intent(getApplicationContext(),SubActivity2.class);
startActivity(newActivity1);
break;
}
}
});
}
submenu:
public class SubActivity extends ListActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// storing string resources into Array
String[] submen_1 = getResources().getStringArray(R.array.submenu_1);
// Binding resources Array to ListAdapter
setListAdapter(new ArrayAdapter<String>(ctx, R.layout.list_item1, R.id.submen1, submen_1));
ListView sublv1 = getListView();
// listening to single list item on click
sublv1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// Launching new Activity on selecting single List Item
Intent newActivity = new Intent(getApplicationContext(),Page1.class);
// sending data to new activity
newActivity.putExtra("position",position);
startActivity(newActivity);
}
});
}
xml main menu:
list_item.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android">
<ImageView
android:id="#+id/option_icon"
android:layout_width="48dp"
android:layout_height="fill_parent"/>
<TextView
android:id="#+id/option_text"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:textSize="16dp" >
</TextView>
sub menu:
list_item1.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android">
<ImageView
android:id="#+id/icon1"
android:layout_width="48dp"
android:layout_height="fill_parent"
android:src="#drawable/ic_action_google_play" />
<TextView
android:id="#+id/submen1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:textSize="16dp" >
</TextView>
Currently you are not defining Hight and Width for LinearLayout in both list_item.xml and list_item1.xml layouts . add height-width as :
In list_item.xml :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android">
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<!-- PUT YOUR ImageView or other xml elements here -->
</LinearLayout>
and do same for list_item1.xml layout

Categories

Resources