简体   繁体   中英

How to show value of EditText in listview each time on button click in android

I have two EditText fields ie name and marks and one Add button.

I have to display EditText values each and every time whenever Add button is clicked.

However,I am only able to display only one single value on listview.

When i clicked again on Add button,its previous value get erased and newer value gets displayed in listview.

I wanna populate whole list in listview.

public class MainActivity extends Activity {
EditText name1;
EditText marks1;
private ListView lv;
ArrayAdapter<String> aa;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState); 
   requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
        WindowManager.LayoutParams.FLAG_FULLSCREEN);
    setContentView(R.layout.activity_main);

    TextView markshee = (TextView)findViewById(R.id.textView3); 
    markshee.setText("");

    Button btnAdd = (Button) findViewById(R.id.button1);
    btnAdd.setOnClickListener(new Button.OnClickListener() {

        public void onClick(View v) {

            try{
                name1 = (EditText)findViewById(R.id.editText1);   
                 String name = name1.getText().toString();

                marks1 = (EditText)findViewById(R.id.editText2);   
                String marks = marks1.getText().toString();


                if(name.equals("") || marks.equals("")){

                    String str="Don't Leave any field blank !";

                    Toast toast = Toast.makeText(MainActivity.this, str, Toast.LENGTH_SHORT);
                    toast.setGravity(Gravity.CENTER, 0, 0);
                    toast.show();
                   }
                   else { 

                        TextView marksheet = (TextView)findViewById(R.id.textView3); 
                        marksheet.setText("Marks Sheet");
                        marksheet.setTextColor(Color.BLUE);

                        TextView nam = (TextView)findViewById(R.id.textView4); 
                        nam.setText("Name");
                        nam.setTextColor(Color.RED);

                        TextView mar = (TextView)findViewById(R.id.textView5); 
                        mar.setText("Marks");
                        mar.setTextColor(Color.RED);

                    name1.setText("");
                    marks1.setText("");

                    lv = (ListView) findViewById(R.id.listView1);
                    lv.setItemsCanFocus(true);

                   ArrayList<String> data = new ArrayList<String>();
                     data.add("  "+name+"                         "+marks);


                     aa =      
                     new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1, data);

                     lv.setAdapter(aa); 

                   }
                }catch(Exception ex)
                {
                    System.out.println(ex.getStackTrace());
                }
         }
    });

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}
 }

Try this: you declare ArrayList is public otherwise it will create each and every time clicking and sotre last items only

 public class MainActivity extends Activity {
 EditText name1;
  EditText marks1;
 private ListView lv;
 ArrayAdapter<String> aa;
 ArrayList<String> data = new ArrayList<String>();
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState); 
 requestWindowFeature(Window.FEATURE_NO_TITLE);
 getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
    WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);

TextView markshee = (TextView)findViewById(R.id.textView3); 
markshee.setText("");

Button btnAdd = (Button) findViewById(R.id.button1);
btnAdd.setOnClickListener(new Button.OnClickListener() {

    public void onClick(View v) {

        try{
            name1 = (EditText)findViewById(R.id.editText1);   
             String name = name1.getText().toString();

            marks1 = (EditText)findViewById(R.id.editText2);   
            String marks = marks1.getText().toString();


            if(name.equals("") || marks.equals("")){

                String str="Don't Leave any field blank !";

                Toast toast = Toast.makeText(MainActivity.this, str, Toast.LENGTH_SHORT);
                toast.setGravity(Gravity.CENTER, 0, 0);
                toast.show();
               }
               else { 

                    TextView marksheet = (TextView)findViewById(R.id.textView3); 
                    marksheet.setText("Marks Sheet");
                    marksheet.setTextColor(Color.BLUE);

                    TextView nam = (TextView)findViewById(R.id.textView4); 
                    nam.setText("Name");
                    nam.setTextColor(Color.RED);

                    TextView mar = (TextView)findViewById(R.id.textView5); 
                    mar.setText("Marks");
                    mar.setTextColor(Color.RED);

                name1.setText("");
                marks1.setText("");

                lv = (ListView) findViewById(R.id.listView1);
                lv.setItemsCanFocus(true);


                 data.add("  "+name+"                         "+marks);


                 aa =      
                 new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1, data);

                 lv.setAdapter(aa); 

               }
            }catch(Exception ex)
            {
                System.out.println(ex.getStackTrace());
            }
     }
});

}

Instead of creating and initializing your data inside onClick , try initializing it in the onCreate method and inside onClick just add the new entry to it:

ArrayList<String> data = new ArrayList<String>();
Button btnAdd = (Button) findViewById(R.id.button1);
btnAdd.setOnClickListener(new Button.OnClickListener(){

     public void onClick(View v) {
          .....
          .....
          .....
          data.add("  "+name+"                         "+marks);
          ....
      }
}

With your existing code, when your onClick method is called, you are creating a new list data every time and adding just a single entry to it, hence it displays only a single value.

UPDATE:

Lets see an example : Lets say have a class from which I need to get incremental value on calling a method getIncrementValue that should return current value +1 every time I call it.

This is the code for it:

public class MyClass{
  public int getIncrementValue(){

    int a = 0;
    a = a+1;
    return a;
  }
}

Now if I call this method like:

MyClass m = new MyClass();
System.out.println(m.getIncrementValue()); //prints  1
System.out.println(m.getIncrementValue()); //prints  1  should print 2 right
System.out.println(m.getIncrementValue()); //prints  1  should print 3 right

You see this, every time it prints only one value instead of incremented value.

This is beacuse every time I call getIncrementValue() , I am declaring and initializing a new variable a = 0 and incrementing it and returning it, hence every time it increments it to 1 and return 1 (instead of 2 and three and so on)

For this I need to change slighlty my class, declare variable a outside that method make it a class variable (in your case declare ArrayList<String> data = new ArrayList<String>(); just after the line ArrayAdapter<String> aa; )

public class MyClass{ int a = 0; public int getIncrementValue(){ a = a+1; return a; } }

Now if I call this method like:

MyClass m = new MyClass();
System.out.println(m.getIncrementValue()); //prints  1
System.out.println(m.getIncrementValue()); //prints  2  should print 2 right
System.out.println(m.getIncrementValue()); //prints  3  should print 3 right

Now you can uderstand why that happens with your code.

So try tweaking your code a little bit and it will be fine.

according to your question i have done something for you.. i have created two Edit text as name and marks and created two lists name as list and list2...and one add button... for run this code your min sdk version should be 11 .. otherwise it will not work....when you enter value on edit text box and click on add button these value will be show on two different list and never erased the previous value..... follow my code...

MainActivity.java

package com.example.textview;

import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;


public class MainActivity extends Activity {

EditText Name, Marks;
Button Add;
ListView lv, lv2;

ArrayList<String> list = new ArrayList<String>();
ArrayAdapter<String> adapter;
ArrayList<String> list2 = new ArrayList<String>();
ArrayAdapter<String> adapter2;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
      Name=(EditText)findViewById(R.id.name);
      Marks=(EditText)findViewById(R.id.marks);

      Add=(Button)findViewById(R.id.add);

      lv=(ListView)findViewById(R.id.list);  
      lv2=(ListView)findViewById(R.id.list2);  

  adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
      lv.setAdapter(adapter);
  adapter2 = new ArrayAdapter<String>(this,    android.R.layout.simple_list_item_activated_1, list2);
      lv2.setAdapter(adapter2);

      Add.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {

                 String name = Name.getText().toString();
                 String marks = Marks.getText().toString();
                    if(name.length() > 0 && marks.length() > 0)
                    {
                        list.add(name);
                        adapter.notifyDataSetChanged();
                        list2.add(marks);
                        adapter2.notifyDataSetChanged();

                    }
            }
            });


}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

 }

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"
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=".MainActivity" >

<ListView
    android:id="@+id/list"
    android:layout_width="match_parent"
    android:layout_height="200dp"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:layout_toLeftOf="@+id/textView2" >

</ListView>

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/list"
    android:layout_marginTop="36dp"
    android:text="Enter name"
    android:textAppearance="?android:attr/textAppearanceMedium" />

<EditText
    android:id="@+id/name"
    android:layout_width="80dp"
    android:layout_height="wrap_content"
    android:layout_alignLeft="@+id/list"
    android:layout_alignRight="@+id/textView1"
    android:layout_below="@+id/textView1"
    android:layout_marginTop="15dp"
    android:ems="10"
    android:inputType="textPersonName" >

    <requestFocus />
</EditText>

<TextView
    android:id="@+id/textView2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/textView1"
    android:layout_alignBottom="@+id/textView1"
    android:layout_marginLeft="28dp"
    android:layout_toRightOf="@+id/textView1"
    android:text="Enter marks"
    android:textAppearance="?android:attr/textAppearanceMedium" />

<ListView
    android:id="@+id/list2"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_above="@+id/textView1"
    android:layout_alignLeft="@+id/textView2"
    android:layout_alignParentTop="true"
    android:layout_alignRight="@+id/textView2" >

</ListView>

<EditText
    android:id="@+id/marks"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBottom="@+id/name"
    android:layout_alignLeft="@+id/textView2"
    android:layout_alignRight="@+id/textView2"
    android:ems="10" />

<Button
    android:id="@+id/add"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/name"
    android:layout_marginTop="33dp"
    android:layout_toRightOf="@+id/name"
    android:text="ADD" />

</RelativeLayout>

and your min sdk version should be 11

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM