简体   繁体   English

重新保存对象,而不是在列表中创建一个新对象

[英]Resaving object instead of creating a new one in list

Solved - Answer is at end of thread 已解决 -答案在线程结尾

I'm creating a notes app. 我正在创建一个笔记应用程序。 And in that app everything is going well so far except that when I'm trying to edit the note (in a recycler view) and I click save, it creates a new one instead of resaving the contents of the existing note . 在该应用程序中,到目前为止一切都进行得很好,除了当我尝试编辑便笺(在回收者视图中)并单击“保存”时, 它会创建一个新的便笺而不是重新保存现有便笺的内容 Because I don't have a way to save it again, that being because I'm not sure how to go about it. 因为我没有办法再次保存它,这是因为我不确定如何去做。 Here is how I handle saving the note in my activity, CreateNoteActivity.java 这是我如何在活动CreateNoteActivity.java中保存笔记的方法

    // FAB
    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
        // Check to see if at least one field is populated with data
            String title = etTitle.getText().toString();
            String description = etDescription.getText().toString();
            title = title.trim(); // Remove whitespaces at the beginning/end
            description = description.trim();

            // Get intent extras
            Intent intent = getIntent();
            String alreadyCreatedTitle = intent.getStringExtra(CreateNoteActivity.EXTRA_TITLE);
            String alreadyCreatedDescription = intent.getStringExtra(CreateNoteActivity.EXTRA_DESCRIPTION);

            // Check to see if note title is empty, if it is, don't save
            if (title == "" || title.isEmpty()) {
                Snackbar snackbar = Snackbar.make(view, "Title may not be empty", Snackbar.LENGTH_SHORT);
                snackbar.show();
                // If the user clicked an already made note and did not change its contents, go back to MainActivity
            } else if (title.equals(alreadyCreatedTitle) && description.equals(alreadyCreatedDescription)) {
                finish();
                CreateNoteActivity.didClick = false;
                // The user is editing a note
            } else if (didClick) {
                // If the title or description is different then resave the note
                if (!title.equals(alreadyCreatedTitle) || !description.equals(alreadyCreatedDescription)) {
                    // TODO: Make it resave the note object

                }
            } else {
                saveNote();
                CreateNoteActivity.didClick = false;

            }
        }

    });
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}

After that, it comes to my MainActivity.java class where onActivityResult() handles the data and saves a new note, or updates the existing note (not yet implemented) 之后,进入我的MainActivity.java类,其中onActivityResult()处理数据并保存新注释,或更新现有注释(尚未实现)

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == 123) {
        if (resultCode == Activity.RESULT_OK) {
            String passedTitle = data.getStringExtra(CreateNoteActivity.EXTRA_TITLE);
            String passedDescription = data.getStringExtra(CreateNoteActivity.EXTRA_DESCRIPTION);
            if (CreateNoteActivity.didClick) { // User is saving an existing note
                // TODO: Resave the existing note object
                // **************************
            } else { // User is creating a new note
                notes.add(new Note(passedTitle, passedDescription));
            }
        }
        refreshAdapter();
        if (resultCode == Activity.RESULT_CANCELED) {
            // Do something if it's cancelled. Happens when you click the back button for example
        }
    }
}

As you can see, i have a variable, "CreateNoteActivity.didClick = false;" 如您所见,我有一个变量“ CreateNoteActivity.didClick = false;”。 of static boolean in this class that I am using to keep track if the user clicked on a note, and it brought them to this activity. 我正在使用此类中的静态布尔值来跟踪用户是否单击了笔记,并将其带到了此活动中。

I keep track of that in my adapter class 我在适配器类中对此进行了跟踪

    @Override
    public void onClick(View view) {
        CreateNoteActivity.didClick = true;
        Log.d("TAG", "onClick() called on row: " + getAdapterPosition());
        Intent intent = new Intent(context, CreateNoteActivity.class);
        intent.putExtra(CreateNoteActivity.EXTRA_TITLE, titleTV.getText().toString());
        intent.putExtra(CreateNoteActivity.EXTRA_DESCRIPTION, descriptionTV.getText().toString());
        ((Activity) context).startActivityForResult(intent, 123);
    }

So when the user clicks a note at a specific index, it passes the intent extras to CreateNoteActivity.java so it can retrieve them, and populate the edit text with their info. 因此,当用户单击特定索引处的注释时,它将意向附加内容传递给CreateNoteActivity.java,以便可以检索它们,并使用其信息填充编辑文本。 So now what I am wanting to do is if the user clicks save, it doesn't make a new note, but instead resaves the old note 因此,现在我要执行的操作是,如果用户单击“保存”,则不会创建新笔记, 而是重新保存旧笔记

I really would appreciate anyones help and feedback with solving this problem. 对于解决此问题的任何人的帮助和反馈,我都非常感谢。 Been stuck on it for a couple hours now and I just don't know how to wrap my head around going for this. 现在已经被困了几个小时,我只是不知道该怎么做。 Thank you very much. 非常感谢你。

My simple notes class 我的简单笔记课

public class Note {

    private String title;
    private String description;

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public Note(String title, String description) {
        this.title = title;
        this.description = description;
    }

    public Note() {
        // Empty
    }


}

Solution

So what I ended up doing was creating a static int and setting it to getAdapterPosition() so that I could always get the position the certain object was at. 因此,我最终要做的是创建一个静态int并将其设置为getAdapterPosition(),这样我就可以始终获取特定对象所在的位置。 I then passed it as an intent extra and retrieved it so that I could mess with it. 然后,我将其作为额外的意图传递并检索了它,以便可以将其弄乱。 Removed it at that specified index, and set a new one at that index. 在指定的索引处将其删除,并在该索引处设置一个新的索引。

        if (CreateNoteActivity.didClick) { // User is saving an existing note
            note.setTitle(passedTitle);
            note.setDescription(passedDescription);
            notes.remove(passedID); // Remove note so I can put that same one at the top
            notes.add(0, note); // Put note at top of list
            CreateNoteActivity.didClick = false;
            recyclerView.scrollToPosition(0); // Scroll to top
        } else { // User is creating a new note
            note.setTitle(passedTitle);
            note.setDescription(passedDescription);
            notes.add(0, note);
            recyclerView.scrollToPosition(0);
        }
    } 

You should also store id of a Note and pass it to be able to edit. 您还应该存储Note id并将其传递以进行编辑。 You can use its position as the id . 您可以将其位置用作id

if (CreateNoteActivity.didClick) { // User is saving an existing note
     Note anote = notes.getItem(passedNoteId);
     anote.setTitle(passedTitle);
     anote.setDescription(passedDescription);
} else { // User is creating a new note
     notes.add(new Note(passedTitle, passedDescription));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Object 控制,同时使用构造函数创建一个新的 - Object control while creating a new one with constructor 创建对象后,创建新对象会更改第一个对象的字段 - After creating an object, creating a NEW object alters the fields of the first one 自动连线存储库更新现有实体,而不是创建一个新实体 - Autowired Repository updates existing entity instead of creating a new one 在 firebase 中更新子代而不是创建新子代!! 与 android 连接 - Update child instead of creating new one in firebase !! connecting it with android recyclerview 如何直接打印Itext Pdf文件而不是创建新文件 - How to print a Itext Pdf file directly instead of creating a new one sbt使用“默认”项目而不是创建新项目 - sbt is using “default” project instead of creating a new one ArrayList重用单个对象,而不是创建新的对象 - ArrayList re-using single Object, instead of creating new ones Jersey @InjectParam创建一个新对象,而不是从Spring获取 - Jersey @InjectParam creating a new Object instead of taking from Spring 有没有办法链接mysql中已有的条目而不是创建一个新的? - Is there a way to link already existing entries in a mysql instead of creating a new one? 从方法参数创建新对象或引用 - Creating new object from method argument or referencing instead
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM