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();
}
Related
To assign data of an ArrayList<String> alKategorien to a spinner auswahl_kategorie, I am using this snippet:
ad = new ArrayAdapter(
this,
android.R.layout.simple_spinner_item,
alKategorien);
ad.setDropDownViewResource(
android.R.layout
.simple_spinner_dropdown_item);
auswahl_kategorie.setAdapter(ad);
I tried to reuse the ArrayAdapter by phrasing it like
if (ad == null) {
ad = new ArrayAdapter(
this,
android.R.layout.simple_spinner_item,
alKategorien);
ad.setDropDownViewResource(
android.R.layout
.simple_spinner_dropdown_item);
auswahl_kategorie.setAdapter(ad);
}
else
{
ad.clear();
ad.addAll(alKategorien);
ad.notifyDataSetChanged();
}
Yet unless ad is null, this yields an empty spinner.
How do I reuse the ArrayAdapter properly?
I have just made a very simple sample.
activity_main.xml:
<?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:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dp"
tools:context=".MainActivity">
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button 1"
android:id="#+id/bt1" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button 2"
android:id="#+id/bt2" />
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button 3"
android:id="#+id/bt3" />
<Button
android:id="#+id/btGetSpinnersValues"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Get Spinners Values" />
</LinearLayout>
item_schreiben.xml:
<?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"
android:padding="10dp">
<TextView
android:id="#+id/tvSample"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Spinner
android:layout_marginBottom="20dp"
android:layout_width="match_parent"
android:layout_height="70dp"
android:id="#+id/auswahl_kategorie" />
</LinearLayout>`
MainActivity.java:
public class MainActivity extends AppCompatActivity {
private final int NO_OF_ITEMS = 3;
Button bt1, bt2, bt3, btGetSpinnersValues;
//Spinner auswahl_kategorie;
ArrayList<String> alKategorien = new ArrayList();
ArrayList<Integer> alDynamicChildren = new ArrayList();
ArrayAdapter ad;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout rootLayout = findViewById(R.id.rootLayout);
bt1 = findViewById(R.id.bt1);
bt2 = findViewById(R.id.bt2);
bt3 = findViewById(R.id.bt3);
btGetSpinnersValues = findViewById(R.id.btGetSpinnersValues);
alKategorien.add("a");
alKategorien.add("b");
alKategorien.add("c");
alKategorien.add("d");
alKategorien.add("e");
setSpinnerAdapter();
for (int i = 0; i < NO_OF_ITEMS; i++) {
View dl_item_schreiben = getLayoutInflater().inflate(R.layout.item_schreiben, null);
rootLayout.addView(dl_item_schreiben);
alDynamicChildren.add(rootLayout.indexOfChild(dl_item_schreiben));
TextView textView = dl_item_schreiben.findViewById(R.id.tvSample);
textView.setText("Spinner " + (i + 1));
Spinner auswahl_kategorie = dl_item_schreiben.findViewById(R.id.auswahl_kategorie);
auswahl_kategorie.setAdapter(ad);
auswahl_kategorie.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
}
bt1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
alKategorien.clear();
alKategorien.add("A");
alKategorien.add("B");
alKategorien.add("C");
alKategorien.add("D");
alKategorien.add("E");
ad.notifyDataSetChanged();// or setSpinnerAdapter();
}
});
bt2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
alKategorien.clear();
alKategorien.add("1");
alKategorien.add("2");
alKategorien.add("3");
alKategorien.add("4");
alKategorien.add("5");
ad.notifyDataSetChanged();// or setSpinnerAdapter();
}
});
bt3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
alKategorien = new ArrayList<>();
alKategorien.add("A");
alKategorien.add("B");
alKategorien.add("C");
alKategorien.add("D");
alKategorien.add("E");
setSpinnerAdapter();
}
});
btGetSpinnersValues.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String msg = "";
LinearLayout parent = (LinearLayout) view.getParent();
for (int i = 0; i < NO_OF_ITEMS; i++) {
Spinner auswahl_kategorie = parent.getChildAt(alDynamicChildren.get(i)).findViewById(R.id.auswahl_kategorie);
msg += "Spinner " + (i +1) + ": " + auswahl_kategorie.getSelectedItem().toString() + "\n";
}
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
}
});
}
private void setSpinnerAdapter() {
if (ad == null) {
ad = new ArrayAdapter(this, android.R.layout.simple_spinner_item, alKategorien);
ad.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//auswahl_kategorie.setAdapter(ad);
} else {
//ad.clear();
//ad.addAll(alKategorien);
ad.notifyDataSetChanged();
}
}
}
I tested the code and spinner changed content for bt1/bt2 clicked. But after bt3 clicked, no more change.
First, when the adapter is created, it is set with alKategorien as the data list, so call ad.clear() just clear alKategorien and ad.addAll(alKategorien); add back an empty list. Therefore those two lines should be removed.
Second, data list cannot be created again (i.e. = new ArrayList<>() and so no more change after bt3 clicked) but can be modified (clear, add, remove) because it acts like a linkage between activity and adapter. If data list is created again by new, then the adapter needs to be created again as linkage broken. There may be other conditions that can break the linkage. Since the code that I mentioned in first point is removed, so issue should be caused by the way of modifying data list which is not shown in the snippet.
So I have been trying to display a list of data from my local mysql server using API calls like getAll,getByID,etc. on the spinner in a drop down style. However when I click on the spinner nothing happens. Here's my code for the passing the data to the spinner:-
public class markAbsentee extends AppCompatActivity implements OnItemSelectedListener{
Button fromDate, toDate, save;
TextView displayFDate, displayTDate;
Spinner genieS;
List genieList;
private Spinner getGenieS;
private List<Genie> getGenieList;
private Button getFromDate;
private Button getToDate;
private Button getSave;
private TextView getDisplayFDate;
private TextView getDisplayTDate;
private DatePickerDialog.OnDateSetListener mDateSetListener, mDateSetListener1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mark_absentee);
getGenieS = (Spinner) findViewById(R.id.geniespinner);
getFromDate = (Button) findViewById(R.id.button2);
getToDate = (Button) findViewById(R.id.button3);
getDisplayFDate = (TextView) findViewById(R.id.fromDate);
getDisplayTDate = (TextView) findViewById(R.id.toDate);
new SpinTask().execute();
//I have called the AsyncTask here which contains the get() API
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Genie selected = (Genie)parent.getSelectedItem();
Toast.makeText(markAbsentee.this, selected.id + " " + selected.name, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
class SpinTask extends AsyncTask<Void, Void, List<Genie>>{
private Exception exception;
protected void onPreExecute(){}
#Override
protected List<Genie> doInBackground(Void... voids) {
GenieService genieService = new GenieService();
return genieService.getAll();
}
protected void onPostexecute(List<Genie> genies){
if(genies == null){
new ArrayList<Genie>();
}else {
List<String> rows = genies.stream().map(genie -> getRow(genie)).collect(Collectors.toList());
ArrayAdapter<Genie> adapter = new ArrayAdapter<Genie>(markAbsentee.this, android.R.layout.simple_spinner_item, genies);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
Toast.makeText(markAbsentee.this, "Clicked", Toast.LENGTH_LONG).show();
genieS.setAdapter(adapter);
}
}
private String getRow(Genie g){
return String.format("%s %s", g.name, g.salary);
}
}
}
Here's the layout of the spinner:-
<?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"
android:background="#drawable/bcak"
android:orientation="vertical"
tools:context="com.codionics.geniem.markAbsentee">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="76dp"
android:layout_marginTop="59dp"
android:text="Enter Absentee"
android:textSize="30dp"
android:textColor="#ffff" />
<Spinner
android:id="#+id/geniespinner"
android:layout_width="350dp"
android:layout_height="wrap_content"
android:layout_alignParentStart="true"
android:layout_below="#+id/textView4"
android:layout_marginStart="20dp"
android:layout_marginTop="27dp"
android:popupBackground="#color/colorPrimary"
android:spinnerMode="dropdown"
android:autofillHints="Select genie" />
</RelativeLayout>
</android.support.constraint.ConstraintLayout>
P.S:- GenieService is the service class for calling the API's. I want to display the name and salary of the person in the spinner drop down list.Thanks in advance for the help.
when you set spinner value it containg only single value like string,integer etc show. when you getting data then it add data into list like below ...
listArray.addAll("Your Value");
then after define array adapter like below and set spinner ..
ArrayAdapter arrayAdapter=new ArrayAdapter(this,android.R.layout.simple_list_item_1,strings);
spinner.setAdapter(arrayAdapter);
then after you called any function on spinner item selection used like below code ...
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
Toast.makeText(getApplicationContext(),"Hello",0).show();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
I have been used Intent to save the data that I want to pass.. this is in login page..
String name = etUsername.getText().toString();
Intent intent = new Intent(getApplicationContext(), Posting.class);
intent.putExtra("myname", name);
this username I want to pass it from login page to my RecyclerView layout by clicking on Add Button in Posting class:
By clicking on AddButton the username should appear in each CardView.
here is the posting class that have AddButton:
public class Posting extends ActionBarActivity {
private RecyclerView myRecyclerView;
private LinearLayoutManager linearLayoutManager;
private RecyclerViewAdapter myRecyclerViewAdapter;
EditText nameField;
Button btnAdd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_posting);
myRecyclerView = (RecyclerView) findViewById(R.id.myrecyclerview);
btnAdd = (Button) findViewById(R.id.addbutton);
Toolbar my_toolbars = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(my_toolbars);
getSupportActionBar().setTitle(R.string.title);
linearLayoutManager =
new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
myRecyclerViewAdapter = new RecyclerViewAdapter(this);
myRecyclerView.setAdapter(myRecyclerViewAdapter);
myRecyclerView.setLayoutManager(linearLayoutManager);
nameField = (EditText) findViewById(R.id.namefield);
btnAdd = (Button) findViewById(R.id.addbutton);
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String newName = nameField.getText().toString();
if (!newName.equals("")) {
myRecyclerViewAdapter.add(0, newName);
TextView textView = (TextView) findViewById(R.id.display);
Intent intent = getIntent();
String name = intent.getStringExtra("myname");
textView.setText(name);
}
}
});
}
and this is the layout of the cardView.
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical"
android:layout_margin="10dp"
card_view:cardCornerRadius="20sp"
card_view:cardElevation="5sp">
<TextView
android:id="#+id/username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="8pt"
android:text="i" />
<View
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#android:color/darker_gray"
android:layout_margin="25dp"/>
<TextView
android:id="#+id/card_item_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="8pt"
android:layout_marginTop="30dp"/>
I want to pass it from login page to this page through TextView with id="username".
how can this be done?
//in posting Activity
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String newName = nameField.getText().toString();
if (!newName.equals("")) {
myRecyclerViewAdapter = new RecyclerViewAdapter(this,newName);
myRecyclerView.setAdapter(myRecyclerViewAdapter);
myRecyclerView.setLayoutManager(linearLayoutManager);
}
});
In RecyclerViewAdapter
//Create Constructor like below:
String name;
Activity context;
public RecyclerViewAdapter(Activity activity,String newName){
this.context=activity;
this.name= newName;
}
#Override
public void onBindViewHolder(RecyclerViewAdapter.ViewHolder holder, int position) {
holder.username.setText(name);
}
I am having trouble with the variable: URL_STRING. I can't seem to add a value from another variable to URL_String. It just null for some reason. Your assistance would be appreciated.
public class HomeScreen extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
ListView listView;
Spinner spinner;
EditText search;
Button bt;
String URL_STRING;
String entity;
String term;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_screen);
listView = (ListView) findViewById(R.id.listView);
spinner = (Spinner) findViewById(R.id.spinner);
search = (EditText) findViewById(R.id.search);
term = search.getText().toString();
bt = (Button) findViewById(R.id.searchBtn);
ArrayAdapter<CharSequence> entityAdapter = ArrayAdapter
.createFromResource(this, R.array.Entities,
android.R.layout.simple_spinner_item);
spinner.setAdapter(entityAdapter);
spinner.setOnItemSelectedListener(this);
}
This is where I am having trouble. URL_STRING is still null
public void addURL(View view) {
if(entity == "Select" && term != null){
URL_STRING = String.format(getResources().getString(R.string.url1),term);
SearchDownloader searchDownloader = new SearchDownloader(this);
searchDownloader.execute();
listView.setVisibility(View.VISIBLE);
}else if(term == null){
Toast.makeText(getApplicationContext(), "Please enter a search term",
Toast.LENGTH_LONG).show();
}else{
URL_STRING = String.format(getResources().getString(R.string.url2), term, entity);
SearchDownloader searchDownloader = new SearchDownloader(this);
searchDownloader.execute();
listView.setVisibility(View.VISIBLE);
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
entity = String.valueOf(spinner.getSelectedItem());
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
entity = null;
}
}
I am not very sure about the adapter and the array being assigned to it.
I have created something which are looking for, Kindly try this, code is available on Github as well have a look at it if i may have missed something. to load the imgae I am using a library called picasso which you can easily import by adding following code to the dependencies block in the build.gradle file like this
compile 'com.squareup.picasso:picasso:2.5.2'
and you would be able to use picasso
public class SpinnerTestTwoActivity extends Activity {
private Spinner url_Spinner;
private Button load_image_Button;
private ImageView url_image_ImageView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_spinner_test_two);
initializeUI();
}
private void initializeUI() {
url_Spinner = (Spinner) findViewById(R.id.SpinnerTestTwoActivity_url_spinner);
load_image_Button = (Button) findViewById(R.id.SpinnerTestTwoActivity_load_image_button);
url_image_ImageView = (ImageView) findViewById(R.id.SpinnerTestTwoActivity_image_from_url_imageView);
String[] url_array = getResources().getStringArray(R.array.url_images);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.simple_spinner_dropdown_item, url_array);
url_Spinner.setAdapter(adapter);
url_Spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String image_url = (String)url_Spinner.getItemAtPosition(position);
Picasso.with(getApplicationContext()).load(image_url).into(url_image_ImageView);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
}
activity_spinner_test_two.xml
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="8dp"
android:gravity="center"
android:orientation="vertical">
<Spinner
android:id="#+id/SpinnerTestTwoActivity_url_spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="4dp" />
<Button
android:id="#+id/SpinnerTestTwoActivity_load_image_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="4dp"
android:text="Load Image"
android:textAllCaps="false" />
<ImageView
android:id="#+id/SpinnerTestTwoActivity_image_from_url_imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_margin="4dp"
android:layout_weight="1"
android:scaleType="fitCenter" />
</LinearLayout>
url_images
This is the array which you will make in the arrays.xml file which is in the res/values directory
<array name="url_images">
<item>https://material-design.storage.googleapis.com/publish/material_v_4/material_ext_publish/0Bx4BSt6jniD7emgtQk5rdEE3bW8/style_icons_system_intro_principles_simple.png</item>
<item>https://material-design.storage.googleapis.com/publish/material_v_4/material_ext_publish/0Bx4BSt6jniD7MGhHV055eGk0R2M/style_icons_system_intro_principles_intuitive.png</item>
<item>https://material-design.storage.googleapis.com/publish/material_v_4/material_ext_publish/0Bx4BSt6jniD7MG80dmpHT0RidGs/style_icons_system_intro_principles_actionable.png</item>
<item>https://material-design.storage.googleapis.com/publish/material_v_4/material_ext_publish/0Bx4BSt6jniD7blViQzF0azNqZU0/style_icons_system_intro_principles_consistent.png</item>
<item>https://material-design.storage.googleapis.com/publish/material_v_4/material_ext_publish/0Bx4BSt6jniD7VXlvR05VSWhPZTg/style_icons_system_grid_geometry2.png</item>
<item>https://material-design.storage.googleapis.com/publish/material_v_4/material_ext_publish/0Bx4BSt6jniD7SUV1b2Z3b3NBazA/style_icons_system_best_do1.png</item>
<item>https://material-design.storage.googleapis.com/publish/material_v_4/material_ext_publish/0Bx4BSt6jniD7azQ4WThPb25NOGc/style_icons_system_best_do3.png</item>
</array>
Output
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>