How to display text from EditText to ListView? - android

I want to display in the listview what I have type in the EditText, so everytime I'm going to input something in the EditText, it will automatically add in the array adn display it using a listview.
Need a help. Thanks.

Have you checked using a ListAdapter? If not, doesnt matter. Here's how it could be done (untested and written by the fly)
public class ListViewExampleActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_listviewexampleactivity);
final Button btn = (Button) findViewById(R.id.btn);
final EditText edt = (EditText) findViewById(R.id.edt);
final ListView listview = (ListView) findViewById(R.id.listview);
final ArrayList<String> list = new ArrayList<>();
final StableArrayAdapter adapter = new StableArrayAdapter(this, android.R.layout.simple_list_item_1, list);
listview.setAdapter(adapter);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (edt.getText().toString() != null) {
adapter.addItem(edt.getText().toString());
}
});
}
private class StableArrayAdapter extends ArrayAdapter<String> {
ArrayList<String> data = new ArrayList<>();
public StableArrayAdapter(Context context, int textViewResourceId,
List<String> objects) {
super(context, textViewResourceId, objects);
this.data = (ArrayList)objects;
}
#Override
public long getItemId(int position) {
String item = getItem(position);
return mIdMap.get(item);
}
public void addItem(String item) {
data.add(item);
notifyDataSetChanged();
}
}

You can use the ArrayAdapter to handle the list of String you want to display.
On the Button click, you can then add the EditText content to the adapter and then notifyDataSetChanged() the adapter so it "redraws" itself and finally clear the EditText content.
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends Activity {
EditText input;
ListView list;
ArrayAdapter<String> adapter;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// android:id="#+id/input"
input = (EditText) findViewById(R.id.input);
// android:id="#+id/list"
list = (ListView) findViewById(R.id.list);
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, new ArrayList<String>());
list.setAdapter(adapter);
}
// android:onClick="addToList"
public void addToList(View view) {
adapter.add(input.getText().toString());
adapter.notifyDataSetChanged();
// Clear the input
input.setText("");
}
}
With a layout similar to:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" />
<EditText
android:id="#+id/input"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Add to list"
android:onClick="addToList" />
</LinearLayout>

Related

SearchView with custom ListView and custom Adaptor

I want to use the SearchView widget to filter Data.
The filtering doesnt work since i switched to a custom layout for the Listview. The ListView gets filled with all Songs i have but then doesnt update when something gets typed into the SearchView. I just want to get SearchView working for Custom ListView. If u have any Helpful Links pls share them with me.
Search Class:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.SearchView;
import java.util.ArrayList;
import univie.g02.t06.tmsd.dummydata.DummyAPIData;
import univie.g02.t06.tmsd.dummydata.DummySong;
import univie.g02.t06.tmsd.MyAdapter;
public class Search extends AppCompatActivity {
ListView listV;
ArrayList<String> listItems = new ArrayList<String>();
ArrayList<String> titles = new ArrayList<String>();
ArrayList<DummySong> listSongs = new ArrayList<DummySong>();
MyAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
listV = (ListView) findViewById(R.id.list_view);
SearchView searchView = (SearchView) findViewById(R.id.search_view);
listSongs = DummyAPIData.getAllDummySongs();
for (int i = 0; i < listSongs.size(); i++) {
listItems.add(listSongs.get(i).getDummyArtistTitle());
titles.add(listSongs.get(i).getDummyTitle());
}
adapter = new MyAdapter(this,
android.R.layout.simple_list_item_1,
listItems);
listV.setAdapter(adapter);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextChange(String query) {
adapter.getFilter().filter(query);
listV.setAdapter(adapter);
return true;
}
#Override
public boolean onQueryTextSubmit(String query){
return true;
}
});
}
}
MyAdapter Class:
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Filterable;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class MyAdapter extends ArrayAdapter implements Filterable {
private List<String> list;
ArrayList<String> origData = new ArrayList<String>();
private Context context;
public MyAdapter(Context context, int resources, ArrayList<String> list) {
super(context, resources, list);
this.list = list;
this.context = context;
this.origData = list;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int pos) {
return list.get(pos);
}
#Override
public long getItemId(int pos) {
return 0;
//just return 0 if your list items do not have an Id variable.
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.customlayout, null);
}
//Handle TextView and display string from your list
TextView listItemText = (TextView)view.findViewById(R.id.list_item_string);
listItemText.setText(list.get(position));
//Handle buttons and add onClickListeners
Button deleteBtn = (Button)view.findViewById(R.id.delete_btn);
deleteBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
//do something
list.remove(position); //or some other task
notifyDataSetChanged();
}
});
return view;
}
}
customlayout.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<TextView
android:id="#+id/list_item_string"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_alignParentLeft="true"
android:paddingLeft="8dp"
android:textSize="18sp" />
<Button
android:id="#+id/delete_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:layout_marginRight="5dp"
android:text="add" />
</RelativeLayout>
activitysearch.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="univie.g02.t06.tmsd.Search">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<SearchView
android:id="#+id/search_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:clickable="true" />
<ListView
android:id="#+id/list_view"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/search_view" />
</RelativeLayout>
</android.support.constraint.ConstraintLayout>
SearchView searchView =(SearchView) findViewById(R.id.searchView);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
adapterQuote.getFilter().filter(s);
listView.setAdapter(adapterQuote);
return true;
}
#Override
public boolean onQueryTextChange(String s) {
adapterQuote.getFilter().filter(s);
return false;
}
});

Listview custom adaptor in android, ONLY to change Font by passing an array adapter

This is my class and this is where i display the data to a list adaptor R.id.listView1 so all i need is a custom adaptor please i'm new to android
and all other tutorials are out of my league.
This is just a small help i require form the community as this help me a great amount.
import android.content.Context;
import android.content.res.AssetManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
public class View_Data extends AppCompatActivity {
public ArrayList<String> datax = new ArrayList<String>(); //used to store data from db
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_data);
final String LOG_TAG = View_Data.class.getSimpleName();
Typeface custom_font = Typeface.createFromAsset(getAssets(), "fonts/AABOHI.TTF"); // this is the custom font i want to use
try {
String table = "questions";
String[] columnsToReturn = {"question_id", "question", "def_font"};
SQLiteDatabase mydatabase = openOrCreateDatabase("Data",MODE_PRIVATE,null);
Typeface font = Typeface.createFromAsset(getAssets(), "fonts/AABOHI.TTF");
Cursor dbCursor = mydatabase.query(table, null,null, null, null, null, null);
dbCursor.moveToFirst();
String temp ;
int i = 0;
ListView listView1 = (ListView) findViewById(R.id.listView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, datax);
listView1.setAdapter(adapter);
while (!dbCursor.isAfterLast()) {
Log.v(LOG_TAG, String.valueOf(dbCursor.getString(0)));
Log.v(LOG_TAG, String.valueOf(dbCursor.getString(1)));
temp = " Question : " + String.valueOf(dbCursor.getString(1)) ;//This is what i want in a custom font
datax.add(temp);
dbCursor.moveToNext();
i++;
}
dbCursor.close();
for (String row : datax) {
Log.v(LOG_TAG, row);
}
} catch (Exception e) {
Log.v(LOG_TAG, e.toString());
}
ListView listView1 = (ListView) findViewById(R.id.listView1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, datax);
listView1.setAdapter(adapter);
}
}
You can go for base adapter for this type of requirement wherein you can have the facility to modify a lot of things. To know and implement base adapter go through the links :
How to customize listview using baseadapter
http://abhiandroid.com/ui/baseadapter-tutorial-example.html
You can easily customize the base adapter for your required data and font.
Create a base adapter as below :
public class CustomAdapter extends BaseAdapter {
Context context;
ArrayList<String> arrayList;
LayoutInflater inflter;
Typeface font;
public CustomAdapter(Context applicationContext, ArrayList<String> arrayList) {
this.context = applicationContext;
this.arrayList = arrayList;
inflter = (LayoutInflater.from(applicationContext));
font = Typeface.createFromAsset(context.getAssets(), "fonts/Questrial-Regular.ttf");
}
#Override
public int getCount() {
return arrayList.size();
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
view = inflter.inflate(R.layout.activity_item, null);
TextView tv = (TextView) view.findViewById(R.id.tv);
tv.setText(arrayList.get(i));
tv.setTypeface(font);
return view;
}
}
Main activity
public class MainActivity extends AppCompatActivity {
ArrayList<String> simpleStringArrayList;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
simpleStringArrayList = new ArrayList<>();
simpleStringArrayList.add("aaa");
simpleStringArrayList.add("bbb");
simpleStringArrayList.add("ccc");
simpleStringArrayList.add("ddd");
simpleStringArrayList.add("eee");
simpleStringArrayList.add("fff");
simpleStringArrayList.add("ggg");
listView = (ListView) findViewById(R.id.listView);
listView= (ListView) findViewById(R.id.listView);
CustomAdapter customAdapter = new CustomAdapter(this, simpleStringArrayList);
listView.setAdapter(customAdapter);
}
}
activity_item
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
activity_main
<?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"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.dell1.myapplication.MainActivity">
<ListView
android:id="#+id/listView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</RelativeLayout>

ListView not showing text on items

I want to display text input from an editText and show it in a listView using an ArrayAdapter, when clicking a button, the listView does gets an item added but without the text :
here is the code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.blink.blink.MainActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="61dp">
<EditText
android:layout_width="280dp"
android:layout_height="60dp"
android:hint="Type a quote .. "
android:id="#+id/quoteField" />
<Button
android:layout_width="wrap_content"
android:layout_height="60dp"
android:text="Add Quote"
android:id="#+id/addQuote"
android:fontFamily="sans-serif-condensed"
android:background="#f6546a"
android:layout_marginLeft="10dp"
android:layout_toRightOf="#id/quoteField" />
</RelativeLayout>
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/quotelistView"
android:foreground="#f6546a"/>
</LinearLayout>
and :
public class MainActivity extends AppCompatActivity {
Button createBtn ;
EditText quoteField;
ListView quotesListView;
ArrayList<String> quotesArrayList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
createBtn = (Button) findViewById(R.id.addQuote);
quoteField = (EditText) findViewById(R.id.quoteField);
quotesListView = (ListView) findViewById(R.id.quotelistView);
quotesArrayList = new ArrayList<>();
createBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
quotesArrayList.add(quoteField.getText().toString());
SetAdapter();
quoteField.setText(" ");
}
});
}
private void SetAdapter()
{
ArrayAdapter<String> Adapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1, quotesArrayList);
quotesListView.setAdapter(Adapter);
}
}
You do not need to reset the adapter everytime you change the data in the array. What you should do is keep a reference to the adapter and call adapter.notifyDataSetChanged() when you change the data in the list
public class MainActivity extends AppCompatActivity {
Button createBtn ;
EditText quoteField;
ListView quotesListView;
ArrayList<String> quotesArrayList;
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
createBtn = (Button) findViewById(R.id.addQuote);
quoteField = (EditText) findViewById(R.id.quoteField);
quotesListView = (ListView) findViewById(R.id.quotelistView);
quotesArrayList = new ArrayList<>();
adapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1, quotesArrayList);
quotesListView.setAdapter(adapter);
createBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
quotesArrayList.add(quoteField.getText().toString());
adapter.notifyDataSetChanged();
quoteField.setText(" ");
}
});
}
}
Try it!
createBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v)
{
quotesArrayList.add(quoteField.getText().toString());
SetAdapter(quotesArrayList);
quoteField.setText(" ");
}
});
}
private void SetAdapter(ArrayList<String> quotesArrayList)
{
ArrayAdapter<String> Adapter = new ArrayAdapter<>(MainActivity.this, android.R.layout.simple_list_item_1, quotesArrayList);
quotesListView.setAdapter(Adapter);
Adapter.notifyDataSetChanged();
}

Save adapter array when new item added to Listview

I just started learn Android. I'm not sure if my question is correct or not. My purpose is when user press on button add item to listview. Each single item (row) have 3 inputs. Currently my code adds item (row) when press on button. But its creating new array and deleting all user inputs. I also almost don't know Java (have very very little OOP skill). Can you answer what am I doing wrong?
Activity:
package com.example.gereltod.test7;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import java.util.ArrayList;
public class SellActivity extends Activity {
ArrayList<Items> items = new ArrayList<Items>();
ItemsAdapter adapter;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sell);
adapter = new ItemsAdapter(this, items);
listView = (ListView) findViewById(R.id.listView_main);
listView.setAdapter(adapter);
}
public void add_item(View view) {
Log.i("clicked add item", "yes");
items.add(new Items("", "", ""));
adapter.notifyDataSetChanged();
}
}
Layout
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/listView_main"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_above="#+id/btn_add_item" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/btn_add_item"
android:id="#+id/btn_add_item"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:onClick="add_item" />
Items Adapter
package com.example.gereltod.test7;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
public class ItemsAdapter extends ArrayAdapter<Items> {
private static class ViewHolder {
TextView name;
TextView qty;
TextView price;
}
public ItemsAdapter(Context context, ArrayList<Items> items) {
super(context, 0, items);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
Items items = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
ViewHolder viewHolder; // view lookup cache stored in tag
if (convertView == null) {
// convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_item, parent, false);
viewHolder = new ViewHolder();
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.list_item, parent, false);
viewHolder.name = (TextView) convertView.findViewById(R.id.edittxt_name);
viewHolder.qty = (TextView) convertView.findViewById(R.id.edittxt_qty);
viewHolder.price = (TextView) convertView.findViewById(R.id.edittxt_price);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.name.setText(items.name);
viewHolder.qty.setText(items.qty);
viewHolder.price.setText(items.price);
return convertView;
}
}
List item
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_weight="1">
<TableRow
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp">
<EditText
android:id="#+id/edittxt_name"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:background="#drawable/input_shape"
android:hint="#string/hint_item_name"
android:padding="5dp"
android:singleLine="true" />
<EditText
android:id="#+id/edittxt_qty"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_weight="0.2"
android:background="#drawable/input_shape"
android:gravity="right"
android:hint="#string/hint_item_qty"
android:inputType="number"
android:padding="5dp"
android:singleLine="true" />
<EditText
android:id="#+id/edittxt_price"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_weight="0.3"
android:background="#drawable/input_shape"
android:gravity="end"
android:hint="#string/hint_item_price"
android:inputType="number"
android:padding="5dp"
android:singleLine="true" />
</TableRow>
</TableLayout>
Edit: Since my English sucks, I can't exactly describe whats going on. So I added screenshot. See here: http://i.imgur.com/Yzw2s7D.jpg
You are creating every time a new list and adding an item to the list and then setting the adapter of single list to listview.
Set the adapter on create of activity and then add items to adapter and call notifyDataSetChanged() method. Here is the code for activity:
public class SellActivity extends Activity {
ArrayList<Items> items = new ArrayList<Items>();
private ItemsAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sell);
ListView listView = (ListView) findViewById(R.id.listView_main);
adapter = new ItemsAdapter(this);
listView.setAdapter(adapter);
}
public void add_item(View view) {
Log.i("clicked add item", "yes");
adapter.add(new Items("", "", ""));
adapter.notifyDataSetChanged();
}
}
In your add_item method you should not create new adapter and new reference to listView. move these lines in your onCreate() method
ItemsAdapter adapter = new ItemsAdapter(this, items);
ListView listView = (ListView) findViewById(R.id.listView_main);
listView.setAdapter(adapter);
add_item should only adding item and notifyDataSetChanged().
I am not quit sure but try this
package com.example.gereltod.test7;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import java.util.ArrayList;
public class SellActivity extends Activity {
ArrayList<Items> items = new ArrayList<Items>();
ItemsAdapter adapter;
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sell);
adapter = new ItemsAdapter(this, items);
listView = (ListView) findViewById(R.id.listView_main);
listView.setAdapter(adapter);
}
public void add_item(View view) {
Log.i("clicked add item", "yes");
items.add(new Items("", "", ""));
adapter.notifyDataSetChanged();
}
}
i have a feeling this should work...
You must change this method . first initialize your adapter into
onCreate() {
adapter = new ItemsAdapter(this, items);
listView = (ListView) findViewById(R.id.listView_main);
listView.setAdapter(adapter);
}
ItemsAdapter adapter;
ListView listView;
public void add_item(View view) {
Log.i("clicked add item", "yes");
items.add(new Items("", "", ""));
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
I think you don't set the information taken from the input to the arraylist so, it doesn't have any information inside.

How to retrieve widgets from Single Layout ArrayAdapters

So I have a Listview full of rows, each with a textview and a spinner. I use an ArrayAdapter to fill in each row. There is a single layout for all the rows.
I want to have a button underneath all the rows that I can press so that it saves all the selections of the spinners in a Text file.
My problem though is I dont know how to reference the spinners anymore since I use the single layout approach. I no longer have unique IDs: (spinner1, spinner2, spinner3, etc.) for each one because they are filled in row by row.
Any advice on how to approach this problem so I can reference each spinner and call their "get text" method?
The more detail the better, thanks in advance!
This is how I would do it: If the model object type of your array doesn't have a variable for the current spinner selection, you need to update your model or extend your Adapter so that you can capture the current selection of the spinner for that item.
In your adapter's getView(), when you create the spinner, add an OnItemSelectedListener to it that updates the model for its corresponding item in the array.
Then when the save button is pressed, you simply loop through the items in the adapter's array and get all the current spinner values.
Here is a code example:
MainActivity.java
package com.example.spinnerdemo;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
public class MainActivity extends Activity {
private static final String TAG = "MainActivity";
private static final String[] mValues = {
"Strongly Agree",
"Agree",
"Neutral",
"Disagree",
"Strongly Disagree"
};
public static class MyModel {
public String text;
public int spinnerVal;
public MyModel(String txt, int val) {
text = txt; spinnerVal = val;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final List<MyModel> items = createItemList();
ListView listView = (ListView) findViewById(R.id.listView1);
final MyListAdapter adapter = new MyListAdapter(this, items);
listView.setAdapter(adapter);
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// here is where we get all the spinner values
Log.d(TAG, "------- save button clicked");
for (MyModel model : items) {
Log.d(TAG, model.text + " : " + mValues[model.spinnerVal]);
}
Log.d(TAG, "-------");
}
});
}
public static class MyListAdapter extends ArrayAdapter<MyModel> {
public MyListAdapter(Context context, List<MyModel> objects) {
super(context, 0, objects);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) parent.getContext().getSystemService(LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.list_item, parent, false);
}
final MyModel model = (MyModel) getItem(position);
TextView textView = (TextView) convertView.findViewById(R.id.textView1);
textView.setText(model.text);
Spinner spinner = (Spinner) convertView.findViewById(R.id.spinner1);
spinner.setAdapter(new ArrayAdapter<String>(parent.getContext(),
android.R.layout.simple_spinner_dropdown_item,
android.R.id.text1, mValues));
// here is where the spinner gets the value from the model
spinner.setSelection(model.spinnerVal);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
// here is where we update the model with the current position of the spinner
model.spinnerVal = position;
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
return convertView;
}
}
private List<MyModel> createItemList() {
List<MyModel> items = new ArrayList<MyModel>();
// initialize with "Neutral" spinner setting
items.add(new MyModel("question 1", 2));
items.add(new MyModel("question 2", 2));
items.add(new MyModel("question 3", 2));
items.add(new MyModel("question 4", 2));
items.add(new MyModel("question 5", 2));
return items;
}
}
activity_main.xml
<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"
tools:context="com.example.spinnerdemo.MainActivity" >
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:text="Save" />
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/button1"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" >
</ListView>
</RelativeLayout>
list_item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:orientation="horizontal" >
<TextView
android:id="#+id/textView1"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="TextView" />
<Spinner
android:id="#+id/spinner1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1" />
</LinearLayout>

Categories

Resources