简体   繁体   中英

Delete a listview item from activity on button click from another activity

I have a MainActivity that shows a listview with items that I add dynamically to it. So far everything works. Now wanted to create a button that should delete the listview item that was clicked on. Here is the code I came with.

MainActivity

package news;

import android.app.Activity;
import android.content.Intent;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {
    ArrayAdapter<String> newslist_adapter;
    ArrayList<String> new_subject = new ArrayList<>();
    ArrayList<String> new_post = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final ListView post_view = findViewById(R.id.news_feed);

        FloatingActionButton add_post_button = findViewById(R.id.post_btn);

        //create click event and pass values of arrays
        post_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                Intent intent = new Intent(getApplicationContext(), full_post_activity.class);
                intent.putExtra("Subject", new_subject);
                intent.putExtra("Post", new_post);
                intent.putExtra("position", id);
//                getApplicationContext().startActivity(intent);
                startActivityForResult(intent, 2);
            }
        });

        //create button connection and create keylistener
        add_post_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, addpost_activity.class);
                startActivityForResult(intent, 1);

            }
        });

    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        final ListView post_view = findViewById(R.id.news_feed);
        if (requestCode == 1) {
            if(resultCode == Activity.RESULT_OK){
                //get subject and post from second activity
                String new_subject_value = data.getStringExtra("newSubject");
                String new_post_value = data.getStringExtra("newPost");
                new_subject.add(new_subject_value);
                new_post.add(new_post_value);
                newslist_adapter = new ArrayAdapter<>(
                        MainActivity.this,
                        android.R.layout.simple_expandable_list_item_1, new_subject);
                post_view.setAdapter(newslist_adapter);

            }
        }
        if (requestCode == 2) {
            if(resultCode == Activity.RESULT_OK){
                String item2delete = data.getStringExtra("id");
                new_subject.remove(item2delete);
                newslist_adapter = new ArrayAdapter<>(
                        MainActivity.this,
                        android.R.layout.simple_expandable_list_item_1, new_subject);
                post_view.setAdapter(newslist_adapter);
            }
        }
    }
} 

SecondActivity

package news;

import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import java.util.ArrayList;

public class full_post_activity extends AppCompatActivity {

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

        final int id = getIntent().getExtras().getInt("id");

        //create view reference
        final TextView subject_edit = findViewById(R.id.subject_input);
        final TextView post_edit = findViewById(R.id.post_input);

        //create button reference
        Button delete_button = findViewById(R.id.full_post_delete_btn);

        //create click event
        delete_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(getApplicationContext(), MainActivity.class);
                intent.putExtra("id", id);
                setResult(Activity.RESULT_OK, intent);
                finish();
            }
        });

        ArrayList<String> subject_array = (ArrayList<String>) getIntent().getSerializableExtra("Subject");
        ArrayList<String> post_array = (ArrayList<String>) getIntent().getSerializableExtra("Post");

        String subject_string = subject_array.get(0);
        String post_string = post_array.get(0);

        //set textview text
        subject_edit.setText(subject_string);
        post_edit.setText(post_string);
    }
}

My problem now is that the delete button doesn't do anything besides returning to the MainActivity . What am I doing wrong?

You cannot get id value to MainActivity. This line in second activity cause problem

final int id = getIntent().getExtras().getInt("id");

In Main Activity, You can put id value using name index "position"

intent.putExtra("position", id);

So you should change them to

In Second Activity

final int id = getIntent().getExtras().getInt("position");

or Main Activity

intent.putExtra("id", id);

UPDATED try this in Main Activity

intent.putExtra("id", position);

If you want to stay in the activity where the delete button is I would suggest creating a getter and a setter for the list behind your ListView(Easily generate them with ALT+INSERT).

You can then make an instance of your MainActivity inside the delete_buttons OnClick methode and get said List with the getter. Remove the Item you need to remove and update the list with your setter, again using your MainActivity instance.

Edit: here are some code samples

Getter and Setter:

public ArrayList<String> getNewPost() {
    return this.new_post;
}

public void setNewPost(ArrayList<String> np) {
    this.new_post = np;
}

delete_button OnClick methode:

delete_button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            MainActivity main=new MainActivity();
            ListView<String> np=main.getNewPost();
            np.remove("StringToRemove"); 
            main.setNewPost(np);
        }
    });

I would also suggest you to make a back_button to check if the list was updated, you can use your old delete_button onclick for that.

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