的ArrayList/ArrayAdapter。新增()函数重写最后一个元素,而不是增加阵列

问题描述:

我正在一个作业这是创建具有2个activites一个书签的应用程序,被称为BookNote ListActivity和称为ManageActivity活动结束。的ArrayList/ArrayAdapter。新增()函数重写最后一个元素,而不是增加阵列

所有打字必须ManageActivity完成并传回给BookNote的名单变化,读,写数据。

我的问题是当我在BookBook活动中调用函数“addBookmark”时。我想要做的是在列表末尾添加一个新的列表项,并在其中添加书签对象信息。

发生什么事是,无论是在列表的末尾的项目是简单地覆盖,而不是创建一个新的项目。

我的代码如下,注释说明我的每个功能的意图。

BookNote活动

public class BookNote extends ListActivity{ 
    private ArrayAdapter<Bookmark> adapter; 
    private final String FILENAME = "bookmarks.txt"; 
    public String title = "EMPTY", url = "EMPTY", note = "EMPTY"; 
    public String bookmarkClicked =""; 
    public int listViewID = 0; 
    public boolean intentListener = false; 
    public int intentReturnCounter = 0; 
    public boolean addBookmarkClicked = false; 
    public ArrayList<Bookmark> bookmarkList; 


    /*When activity is called, list is populated by readData(), addBookmarkClicked is reset to false, intentLister is changed to true if returning from ManageActivity, 
     if intentListener is true, addBookmarkClicked will be changed to true if AddBookmark is clicked from the BookNote menubar, a bookmark object will be created with information 
     passed back from ManageActivity, and if addBookmarkClicked is true, the bookmark object will be added to the end of the list, otherwise it will be inserted in the same 
     list element from which was chosen to edit.*/ 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 


     bookmarkList = readData(); 
     adapter = new ArrayAdapter<Bookmark>(this, android.R.layout.simple_list_item_1, bookmarkList); 
     setListAdapter(adapter); 

     addBookmarkClicked = false; 
     intentListener = false; 



      intentListener = getIntent().getBooleanExtra("listen", false); 

      if (intentListener == true) { 
       addBookmarkClicked = getIntent().getExtras().getBoolean("addBookmarkClicked", false); 
       title = getIntent().getExtras().getString("title"); 
       url = getIntent().getExtras().getString("url"); 
       note = getIntent().getExtras().getString("note"); 
       listViewID = getIntent().getExtras().getInt("listViewID"); 
       Bookmark bookmark = new Bookmark(title, url, note); 
       Toast.makeText(getApplicationContext(), "Intent return: True", Toast.LENGTH_SHORT).show(); 
       intentListener = false; 

       if (addBookmarkClicked == true) { 
        addBookmark(bookmark); 
        Toast.makeText(getApplicationContext(), "Bookmark Added", Toast.LENGTH_SHORT).show(); 
        addBookmarkClicked = false; 
       } else { 
        insertBookmark(bookmark, listViewID); 
        Toast.makeText(getApplicationContext(), "Bookmark Edited", Toast.LENGTH_SHORT).show(); 
       } 
       //writeData(); 
     } 
    } 



    //reads data when app runs and fills arrayadapter and list with items saved to bookmarks.txt 
    private ArrayList<Bookmark> readData(){ 
     ArrayList<Bookmark> bookmarks = new ArrayList<>(); 

     try { 
      FileInputStream fis = openFileInput(FILENAME); 
      Scanner scanner = new Scanner(fis); 
      if (scanner.hasNext()){ 
       String titleScan = scanner.nextLine(); 
       String urlScan = scanner.nextLine(); 
       String noteScan = scanner.nextLine(); 
       Bookmark bookmark = new Bookmark(titleScan, urlScan, noteScan); 
       bookmarks.add(bookmark); 
      }else{ 
       Bookmark bookmark = new Bookmark("Example Title", "Example URL", "Example Note"); 
       bookmarks.add(bookmark); 
      } 
      scanner.close(); 
     } catch (FileNotFoundException e) { 
     } 
     return bookmarks; 
    } 

    private void writeData(){ 
     try { 
      FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE); 
      OutputStreamWriter osw = new OutputStreamWriter(fos); 
      BufferedWriter bw = new BufferedWriter(osw); 
      PrintWriter pw = new PrintWriter(bw); 

      for(int i = 0; i < adapter.getCount(); i++){ 
       Bookmark bookmark = adapter.getItem(i); 
       pw.println(bookmark.getTitle() + "\n" + bookmark.getUrl() + "\n" + bookmark.getNote()); 
      } 
      pw.close(); 
     } catch (FileNotFoundException e) { 
      Log.e("Write ERR", "Cannot save: " + e.getMessage()); 
      e.printStackTrace(); 
      Toast.makeText(BookNote.this, "Error saving", Toast.LENGTH_SHORT).show(); 
     } 
    } 

    //If addBookmark menu item is clicked, this will be called to add a bookmark to the end of the ArrayAdapter. 
    private void addBookmark(Bookmark bookmark){ 
     adapter.add(bookmark); 
     writeData(); 
    } 


    //Calls ManageActivity and reports information about app. 
    public void gotoManageActivity(boolean addBookmarkClicked){ 
     Intent manageIntent = new Intent(this, ManageActivity.class); 
     Bundle extras = new Bundle(); 
     extras.putString("bookmark", bookmarkClicked); 
     extras.putBoolean("addBookmarkClicked", addBookmarkClicked); 
     extras.putInt("listViewID", listViewID); 
     manageIntent.putExtras(extras); 
     startActivity(manageIntent); 
    } 



    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     // Handle action bar item clicks here. The action bar will 
     // automatically handle clicks on the Home/Up button, so long 
     // as you specify a parent activity in AndroidManifest.xml. 
     int id = item.getItemId(); 

     //noinspection SimplifiableIfStatement 
     if (id == R.id.action_add) { 
      addBookmarkClicked = true; 
      gotoManageActivity(addBookmarkClicked); 
      return true; 
     } 

     return super.onOptionsItemSelected(item); 
    } 
} 

ManageActivity

public class ManageActivity extends AppCompatActivity { 

    private String title = "EMPTY", url = "EMPTY", note = "EMPTY"; 
    private boolean listener = true; 
    private boolean addBookmarkClicked = false; 



/* When activity starts, check for addBookmarkClicked status, create book */ 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.manage_layout); 

     addBookmarkClicked = getIntent().getExtras().getBoolean("addBookmarkClicked", false); 

     String bookmarkString = ""; 
     bookmarkString = getIntent().getExtras().getString("bookmark"); 
     if(bookmarkString != null && bookmarkString.length() > 0) { 
      if (bookmarkString.length() != 0) { 
       String[] stringArray = bookmarkString.split("\\n"); 
       title = stringArray[0]; 
       url = stringArray[1]; 
       note = stringArray[2]; 
       updateTextViews(); 
      } 
     } 
     else { updateTextViews(); 
     } 
    } 

    @Override 
    public void onBackPressed(){ 
     Intent bookNoteIntent = new Intent(this, BookNote.class); 
     Bundle extras = new Bundle(); 

     if(title.length() == 0 || title == null){title= "Empty";} 
     if(url.length() == 0 || url == null){ url = "Empty";} 
     if(note.length() == 0 || url == null) { note = "Empty";} 

     extras.putString("title", title); 
     extras.putString("url", url); 
     extras.putString("note", note); 
     extras.putBoolean("listen", listener); 
     extras.putBoolean("addBookmarkClicked", addBookmarkClicked); 
     bookNoteIntent.putExtras(extras); 
     startActivity(bookNoteIntent); 
    } 
+1

为什么'onBackPressed'你开始'BookNote'活动???只需按下“返回”按钮,即可进入该活动 – pskink

+3

您已经提供了近400行代码。请减少到[mcve]。 –

+0

@pskink只是用来传回信息,而不是写一个新的函数来做。 – sircrisp

大问题!几周前,我也必须亲自处理这个问题。

最主要的是,您将需要重新实例化您的案例中的ArrayAdapteradapter

现在你做正确的第一步:

bookmarkList = readData(); 
adapter = new ArrayAdapter<Bookmark>(this, android.R.layout.simple_list_item_1, bookmarkList); 
setListAdapter(adapter); 

但是,试图更新列表时,你会再次做到这一点:我相信你正确添加新的书签,但你需要重新创建列表视图的ArrayAdapter。

编辑: 我相信我发现了危险。 就在这里,您需要重新实例化ArrayAdapter,如前所述。

private void addBookmark(Bookmark bookmark){ 
    adapter.add(bookmark); 
    writeData(); 
} 

基本上,只要你更新的数据要在列表中显示出来,你需要做这一步......

+0

我尝试添加以下至收藏本站(),但仍得到相同的结果 '适配器=新ArrayAdapter (这一点,android.R.layout.simple_list_item_1,bookmarkList);'' setListAdapter(适配器);'' 适配器.add(书签);' 我误解了你? – sircrisp

+0

我想你应该将书签添加到bookmarkList,然后执行'adapter = new ArrayAdapter (this,android.R.layout.simple_list_item_1,bookmarkList);''和'setListAdapter(adapter);' – cdslijngard

+0

这样做只是给我2添加到列表中的重复项目,并且任何时候我尝试添加新项目时,都会用2个新重复项覆盖2个重复项目。 我添加了'bookmarkList.add(书签);'在其余的像你之前建议的那样。 – sircrisp