3

I'm a newbie and I've been trying to develop a contacts application along with another to-do app, but this is a question related to my contacts app.

The inserting and Viewing and Deletion functions work properly but the only problem is that no matter what item I choose to delete on the ListView, it always deletes the top most item.

Here's some code:

MainActivity:

 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        lv=(ListView) findViewById(R.id.listView1);
        im=(ImageButton) findViewById(R.id.add);
        ii=(ImageButton) findViewById(R.id.image);
        list = new ArrayList<HashMap<String,String>>();//memory allocation
        list = db.getvalues();

        ListAdapter ad= new SimpleAdapter(MainActivity.this, list,  R.layout.custom, new String[]{"id","name"}, new int[]{R.id.id,R.id.name});
        lv.setAdapter(ad);
    lv.setOnItemLongClickListener(new OnItemLongClickListener() {

            @Override
            public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                                           int arg2, long arg3) {
                // TODO Auto-generated method stub
                TextView numtask = (TextView) arg1.findViewById(R.id.name);
                phnum = numtask.getText().toString();
                registerForContextMenu(lv);
                return false;
            }
        });


        ii.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Intent i =new Intent(MainActivity.this,Main1Activity.class);
                startActivity(i);
            }
        });


    }



    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo   menuInfo)
    {
        super.onCreateContextMenu(menu, v, menuInfo);
        menu.setHeaderTitle("Select The Action");
        menu.add(0, v.getId(), 1, "DELETE");

    }

    public boolean onContextItemSelected(MenuItem item){


        String number=phnum;



         if(item.getTitle()=="DELETE"){
            TextView id1=(TextView) findViewById(R.id.id);
            db.deleterow(id1.getText().toString());
            Toast.makeText(MainActivity.this,"Task Deleted!", Toast.LENGTH_SHORT).show();
             list = new ArrayList<HashMap<String,String>>();//memory allocation
             list = db.getvalues();

             ListAdapter ad= new SimpleAdapter(MainActivity.this, list,  R.layout.custom, new String[]{"id","name"}, new int[]{R.id.id,R.id.name});
             lv.setAdapter(ad);


    }else{
        return false;
    }
    return true;
}

I'm not going to add the DBConnector class that extends from the SQLiteOpenHelper class as it contains functions that work because the database is being populated and items are being deleted, so I don't think there is a problem with that. However, if you want me to add that I shall do so if you want me to...

Here's the custom.xml file:

<?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:orientation="vertical" >

<TextView
    android:id="@+id/id"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Small Text"
    android:textAppearance="?android:attr/textAppearanceSmall" />

<TextView
    android:id="@+id/name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Large Text"
    android:textStyle="bold"
    android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>

Here's the deleterow method withing the DBconnector class:

public void deleterow(String numid) {


        // TODO Auto-generated method stub
        SQLiteDatabase sb = this.getWritableDatabase();
        String sq = "DELETE FROM user WHERE id="+numid+";";
        sb.execSQL(sq);
    }

Also, I need suggestions as to how I can not display the id numbers along with the names in the ListView.

Please help me guys! I'm banking on all of you!

  • Your problem, most likely, is here: `TextView id1=(TextView) findViewById(R.id.id);` Assuming that this `TextView` is in a `ListView` row, calling `findViewById()` on the activity can return *any* of the `TextView` widgets with that ID, and you have one per row. Context menus have been considered obsolete for five years, so my memory on how they work is fuzzy. However, there is a recipe for getting at the `position` that triggered the context menu in your `onContextItemSelected()` method. – CommonsWare Jan 18 '16 at 07:33
  • Is there any other menu I can use in order to find the position of the item easily? – Android Self-learner Jan 18 '16 at 07:41

1 Answers1

2

You are calling TextView id1=(TextView) findViewById(R.id.id); in onContextItemSelected(MenuItem item) method so it will return first item's text because you have not given selected item's View.

Solution to your problem is AdapterContextMenuInfo. it is used for getting extra menu information provided to the onCreateContextMenu(ContextMenu, View, ContextMenuInfo) callback when a context menu is brought up for this AdapterView.

You can get the selected item's View then get text from TextView in your case.

Here is modified onContextItemSelected(MenuItem item) method.

public boolean onContextItemSelected(MenuItem item){
        String number=phnum;
        if(item.getTitle()=="DELETE"){
            AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
            TextView id1=((TextView) info.targetView).findViewById(R.id.id);
            db.deleterow(id1.getText().toString());
            Toast.makeText(MainActivity.this,"Task Deleted!", Toast.LENGTH_SHORT).show();
            list = new ArrayList<HashMap<String,String>>();//memory allocation
            list = db.getvalues();
            ListAdapter ad= new SimpleAdapter(MainActivity.this, list,  R.layout.custom, new String[]{"id","name"}, new int[]{R.id.id,R.id.name});
            lv.setAdapter(ad);
        }else{
            return false;
        }
    return true;
}
Rajesh Jadav
  • 12,801
  • 5
  • 53
  • 78