Question

I'm very new to Android Dev/Java and I'm following a tutorial online and trying to create a simple To Do list application for Android. It looks the tutorial is a bit outdated and relies on the DPAD to navigate up and down the list of tasks in order to target a list item and delete it using the "Delete Button" in the applications menu. I am having a hard time trying to figure out how to "select" a list item on click and delete it using the "delete" button. Right now when a click a list item it does nothing, so the application doesn't know which is selected, when I click the delete button. Here is my XML and Java code. Any insight will be very helpful.

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" >

    <EditText
        android:id="@+id/textItem"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:ems="10" />

    <Button
        android:id="@+id/btnAdd"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/textItem"
        android:layout_below="@+id/textItem"
        android:text="@string/add" />

    <ListView
        android:id="@+id/listItems"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/btnAdd"
        android:layout_alignRight="@+id/btnAdd"
        android:layout_below="@+id/btnAdd"
        android:layout_marginTop="20dp" >
    </ListView>
</RelativeLayout>

JAVA

    package com.example.todo;

import java.util.ArrayList;  
import java.util.Calendar;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle; 
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnKeyListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements View.OnClickListener, DialogInterface.OnClickListener, OnKeyListener {

    EditText textItem;
    Button btnAdd;
    Button btnDelete;
    ListView listItems;

    ArrayList<String> toDoItems;
    ArrayAdapter<String> aa;

    String[] date = {"Movie", "Dinner", "Drinks"};
    String[] gym = {"Cardio", "Upper Body", "Lower Body"};
    String[] meeting = {"30min Meeting", "1 Hour Meeting", "2 Hour Meeting"};
    String[] homework = {"Paper", "Exercise", "Assignment"};
    String[] project = {"App", "Web", "Graphic Design"};
    String currentMenu;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textItem = (EditText)findViewById(R.id.textItem);
        btnAdd = (Button)findViewById(R.id.btnAdd);
        btnDelete = (Button)findViewById(R.id.btnDelete);
        listItems = (ListView)findViewById(R.id.listItems);

        btnAdd.setOnClickListener(this);
        textItem.setOnKeyListener(this);

        toDoItems = new ArrayList<String>();
        aa = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, toDoItems);
        listItems.setAdapter(aa);

        /*--Set heading to todays Date--*/
            TextView tvDisplayDate = (TextView) findViewById(R.id.heading);
            final Calendar c = Calendar.getInstance();
            int yy = c.get(Calendar.YEAR);
            int mm = c.get(Calendar.MONTH);
            int dd = c.get(Calendar.DAY_OF_MONTH);

            // set current date into textview
            tvDisplayDate.setText(new StringBuilder()
            // Month is 0 based, just add 1
            .append(mm + 1).append("/").append(dd).append("/").append(yy));

    }

    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        MenuItem item;
        item = menu.add("delete");
        item.setIcon(R.drawable.remove);
        item = menu.add("date");
        item.setIcon(R.drawable.date);
        item = menu.add("gym");
        item.setIcon(R.drawable.gym);
        item = menu.add("meeting");
        item.setIcon(R.drawable.meeting);
        item = menu.add("homework");
        item.setIcon(R.drawable.homework);
        item = menu.add("project");
        item.setIcon(R.drawable.project);
        return true;
    }

    public boolean onOptionsItemSelected(MenuItem item) {
        super.onOptionsItemSelected(item);
        if (item.hasSubMenu() == false) {
            if (item.getTitle() == "date") {
                currentMenu = "date";
                this.displayPopup("Date Options", this.date);
            }
            if (item.getTitle() == "gym") {
                currentMenu = "gym";
                this.displayPopup("Gym Options", this.gym);
            }
            if (item.getTitle() == "meeting") {
                currentMenu = "meeting";
                this.displayPopup("Meeting Options", this.meeting);
            }
            if (item.getTitle() == "homework") {
                currentMenu = "homework";
                this.displayPopup("Homework Options", this.homework);
            }
            if (item.getTitle() == "project") {
                currentMenu = "project";
                this.displayPopup("Project Options", this.project);
            }
            if(item.getTitle() == "delete") {
                int index = listItems.getSelectedItemPosition();
                this.deleteItem(index);
            }
        }
        return true;
    }

    private void addItem(String item) { 
        if (item.length() > 0 ) { 
            Toast.makeText(getApplicationContext(), item+" added", Toast.LENGTH_SHORT).show();
            this.toDoItems.add(item);
            this.aa.notifyDataSetChanged();
            this.textItem.setText("");
        }
    }

    private void deleteItem(int itemId) {
        if (itemId >=0) {
            String itemName = (String)listItems.getItemAtPosition(itemId);
            Toast.makeText(getApplicationContext(), itemName+" delete", Toast.LENGTH_SHORT).show();
            this.toDoItems.remove(itemId);
            aa.notifyDataSetChanged();
        }
    }

    private void displayPopup(String title, String[] items) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(title);
        builder.setItems(items, this);
        builder.show();
    }

    @Override
    public void onClick(View v) {
        if (v == this.btnAdd) { 
            this.addItem(this.textItem.getText().toString());
        }
    }


    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if (event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_DPAD_CENTER) { 
            this.addItem(this.textItem.getText().toString());
        }
        return false;
    }

    @Override
    public void onClick(DialogInterface dialog, int item) {
        if (currentMenu == "date") this.addItem(date[item]);
        if (currentMenu == "gym") this.addItem(gym[item]);
        if (currentMenu == "meeting") this.addItem(meeting[item]);
        if (currentMenu == "homework") this.addItem(homework[item]);
        if (currentMenu == "project") this.addItem(project[item]);


    listItems.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
            listItems.setSelection(position);
            view.setSelected(true); 
        }
    });}
}
Was it helpful?

Solution 2

Selecting and clicking are 2 different things.

Override listview.setOnItemClickListener and set your clicked list item selected. Then your delete will work.

listView.setOnItemClickListener(new OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
        listview.setSelection(position);
        view.setSelected(true); 
    }
});

You should try this tutorial to learn more about listview: http://www.vogella.com/tutorials/AndroidListView/article.html

OTHER TIPS

The way i see it, you have to options, in both you'll have to use the onItemClick:

the first, is to delete the item when you click on it

listItems.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        // remove the item from the array
        toDoItems.remove(position);
        // call a UI update for the list
        aa.notifyDataSetChanged();
    }
});

the second, is to store the clicked item position, and then call the delete action once user has clicked on the delete button from the menu.

int selectedItem = -1;
listItems.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        //save the clicked item position 
        // and the when the delete button is pressed, use it.
        // keep in mind that this is not that good if you are using recycled list
        selectedItem = position;            }
});

any way, i would suggest start using an updated tutorial first...

Extend from ListActicity and override the method onListItemClicked.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top