Sunday, March 1, 2015

103 MySuperHero Android Add Edit Delete ListView Item


.
103 MySuperHero Android Add Edit Delete ListView Item
Users typically would want to be able to modify their list of heroes such as adding new heroes and edit or delete the existing ones.

0) Starting Up

Continue from the previous tutorial or download startup files.

1) Add Item

File: SuperHeroesActivity.java
package com.example.mysuperhero;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class SuperHeroesActivity extends Activity {
        Button btnAddSuperHero;
        ListView lvwSuperHeroes;
        String[] strSuperHeroes;
        ArrayAdapter adpSuperHeroes;
        
        @Override
        protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_super_heroes);
                setLvwSuperHeroes();
                setBtnAddSuperHero();
        }
        @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_super_heroes, menu);
                return true;
        }
         private void setLvwSuperHeroes(){
                 //bind object
        lvwSuperHeroes = (ListView) findViewById(R.id.lvw_superheroes);
               
        //Add new values to array
        strSuperHeroes =new String[] {"Superman","Spiderman","Batman","Ironman","Ultraman", "Pacman", "Roboman"};
               
        //Create ArrayList from strSuperHeroes
        List<String> values = new ArrayList<String>(Arrays.asList(strSuperHeroes));
               
        //Create Adapter to load ArrayList
        adpSuperHeroes = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, values);
               
        //Plug adpSuperHeroes to lvwSUperHeroes
        lvwSuperHeroes.setAdapter(adpSuperHeroes);
               
        //set onclick listener for listview
        lvwSuperHeroes.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                editSuperHero(position, ((TextView) view).getText().toString());
            }
                });
            }
                private void setBtnAddSuperHero() {
                        btnAddSuperHero = (Button) findViewById(R.id.btn_add_superhero);
                        btnAddSuperHero.setOnClickListener(new OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                        addSuperHero();
                                }
                        });
                }
                private void editSuperHero(int position, String text){
                Toast.makeText(getApplicationContext(),"Edit SuperHero.\nPosition:"+position+"\nText:"+text+"\n",
                        Toast.LENGTH_SHORT).show();        
            }
            private void addSuperHero(){
                Toast.makeText(getApplicationContext(),"Add SuperHero.",
                        Toast.LENGTH_SHORT).show();  
                adpSuperHeroes.add("New Hero");
                adpSuperHeroes.notifyDataSetChanged();
                //scroll to the bottom
                lvwSuperHeroes.smoothScrollToPosition(adpSuperHeroes.getCount() -1);
            }
}
OUTCOME.

2) Edit Item

File: SuperHeroesActivity.java
package com.example.mysuperhero;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class SuperHeroesActivity extends Activity {
        Button btnAddSuperHero;
        ListView lvwSuperHeroes;
        String[] strSuperHeroes;
        ArrayAdapter adpSuperHeroes;
        
        @Override
        protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_super_heroes);
                setLvwSuperHeroes();
                setBtnAddSuperHero();
        }
        @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_super_heroes, menu);
                return true;
        }
         private void setLvwSuperHeroes(){
                 //bind object
        lvwSuperHeroes = (ListView) findViewById(R.id.lvw_superheroes);
               
        //Add new values to array
        strSuperHeroes =new String[] {"Superman","Spiderman","Batman","Ironman","Ultraman", "Pacman", "Roboman"};
               
        //Create ArrayList from strSuperHeroes
        List<String> values = new ArrayList<String>(Arrays.asList(strSuperHeroes));
               
        //Create Adapter to load ArrayList
        adpSuperHeroes = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, values);
               
        //Plug adpSuperHeroes to lvwSUperHeroes
        lvwSuperHeroes.setAdapter(adpSuperHeroes);
               
        //set onclick listener for listview
        lvwSuperHeroes.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                editSuperHero(position, ((TextView) view).getText().toString());
            }
                });
            }
                private void setBtnAddSuperHero() {
                        btnAddSuperHero = (Button) findViewById(R.id.btn_add_superhero);
                        btnAddSuperHero.setOnClickListener(new OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                        addSuperHero();
                                }
                        });
                }
                private void editSuperHero(int position, String text){
                Toast.makeText(getApplicationContext(),"Edit SuperHero.\nPosition:"+position+"\nText:"+text+"\n",
                        Toast.LENGTH_SHORT).show();
                //recreate new superheroes string array
                String[] strNewSuperHeroes = new String[adpSuperHeroes.getCount()];
                    for (int i = 0; i < adpSuperHeroes.getCount(); i++) {
                        if (i != position) {
                            strNewSuperHeroes[i]= (String) adpSuperHeroes.getItem(i);
                        } else {
                            strNewSuperHeroes[i]= (String) adpSuperHeroes.getItem(i);
                            strNewSuperHeroes[i] += " Edited";
                        }
                    }
               
                //clear adapter
                adpSuperHeroes.clear();
               
                //reassign new superheroes string array to adapter
                adpSuperHeroes.addAll(strNewSuperHeroes);
               
                //notify apps that adapter has changed
                adpSuperHeroes.notifyDataSetChanged();
                //scroll to the bottom
                lvwSuperHeroes.smoothScrollToPosition(adpSuperHeroes.getCount() -1);               
            }
            private void addSuperHero(){
                Toast.makeText(getApplicationContext(),"Add SuperHero.",
                        Toast.LENGTH_SHORT).show();  
                adpSuperHeroes.add("New Hero");
                adpSuperHeroes.notifyDataSetChanged();
                //scroll to the bottom
                lvwSuperHeroes.smoothScrollToPosition(adpSuperHeroes.getCount() -1);
            }
}
You may get error for using “addAll” method.
Error: Call requires API level 11
Solution: Edit AndroidManifest.xml and set minSdkVersion=11
 
OUTCOME.

3) Delete Item

We use onItemLongClickListener to trigger the deleteSuperHero method
File: SuperHeroesActivity.java
package com.example.mysuperhero;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class SuperHeroesActivity extends Activity {
        Button btnAddSuperHero;
        ListView lvwSuperHeroes;
        String[] strSuperHeroes;
        ArrayAdapter adpSuperHeroes;
        
        @Override
        protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.activity_super_heroes);
                setLvwSuperHeroes();
                setBtnAddSuperHero();
        }
        @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_super_heroes, menu);
                return true;
        }
         private void setLvwSuperHeroes(){
                 //bind object
        lvwSuperHeroes = (ListView) findViewById(R.id.lvw_superheroes);
               
        //Add new values to array
        strSuperHeroes =new String[] {"Superman","Spiderman","Batman","Ironman","Ultraman", "Pacman", "Roboman"};
               
        //Create ArrayList from strSuperHeroes
        List<String> values = new ArrayList<String>(Arrays.asList(strSuperHeroes));
               
        //Create Adapter to load ArrayList
        adpSuperHeroes = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, values);
               
        //Plug adpSuperHeroes to lvwSUperHeroes
        lvwSuperHeroes.setAdapter(adpSuperHeroes);
               
        //set onclick listener for listview
        lvwSuperHeroes.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                editSuperHero(position, ((TextView) view).getText().toString());
            }
                });
      //set onItemLongClickListener
        lvwSuperHeroes.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            public boolean onItemLongClick(AdapterView<?> arg0, View v,
                    int index, long arg3) {
                    deleteSuperHero(index);
                    //Toast.makeText(MainActivity.this,lvwSuperHeroes.getItemAtPosition(index).toString(), Toast.LENGTH_LONG).show();
                return true;
            }
        });  
            }
                private void setBtnAddSuperHero() {
                        btnAddSuperHero = (Button) findViewById(R.id.btn_add_superhero);
                        btnAddSuperHero.setOnClickListener(new OnClickListener() {
                                @Override
                                public void onClick(View view) {
                                        addSuperHero();
                                }
                        });
                }
                private void editSuperHero(int position, String text){
                Toast.makeText(getApplicationContext(),"Edit SuperHero.\nPosition:"+position+"\nText:"+text+"\n",
                        Toast.LENGTH_SHORT).show();
                //recreate new superheroes string array
                String[] strNewSuperHeroes = new String[adpSuperHeroes.getCount()];
                    for (int i = 0; i < adpSuperHeroes.getCount(); i++) {
                        if (i != position) {
                            strNewSuperHeroes[i]= (String) adpSuperHeroes.getItem(i);
                        } else {
                            strNewSuperHeroes[i]= (String) adpSuperHeroes.getItem(i);
                            strNewSuperHeroes[i] += " Edited";
                        }
                    }
               
                //clear adapter
                adpSuperHeroes.clear();
               
                //reassign new superheroes string array to adapter
                adpSuperHeroes.addAll(strNewSuperHeroes);
               
                //notify apps that adapter has changed
                adpSuperHeroes.notifyDataSetChanged();
                //scroll to the bottom
                lvwSuperHeroes.smoothScrollToPosition(adpSuperHeroes.getCount() -1);                
            }
            private void addSuperHero(){
                Toast.makeText(getApplicationContext(),"Add SuperHero.",
                        Toast.LENGTH_SHORT).show();  
                adpSuperHeroes.add("New Hero");
                adpSuperHeroes.notifyDataSetChanged();
                //scroll to the bottom
                lvwSuperHeroes.smoothScrollToPosition(adpSuperHeroes.getCount() -1);
            }
            private void deleteSuperHero(int position){
            adpSuperHeroes.remove(adpSuperHeroes.getItem(position));
            adpSuperHeroes.notifyDataSetChanged();
    }
}
OUTCOME.
Ironman, Ultraman and Pacman has been removed from the list

DOWNLOAD


.

No comments:

Post a Comment