我试图从EditText字段中获取输入文本,保存String,然后将其添加/保存到另一个Java ArrayList中的class中。 (我的MainActivity显示我已存储在facts中的所有ArrayList,这是可行的。)但是,从EditText向String添加新的ArrayList无效。

谢谢您的帮助!


FactBook.java

 public class FactBook {
 public ArrayList<String> mFacts = new ArrayList<String>(Arrays.asList(
         "Quote 1",
         "Quote 2"));

 public String getFact() {

     String fact = "";
     Random randomGenerator = new Random();
     int randomNumber = randomGenerator.nextInt(mFacts.size());
     fact = mFacts.get(randomNumber);
     return fact;
 }

 public void addFact(String thought) {
     mFacts.add(thought);
 };

InputActivity.java

 public class InputActivity extends AppCompatActivity {

 private Button mSaveButton;
 private EditText mTextThought;
 private FactBook mFactBook = new FactBook();


 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_input);
 Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
 setSupportActionBar(toolbar);

 mSaveButton = (Button) findViewById(R.id.saveButton);
 mTextThought = (EditText) findViewById(R.id.thoughtText);


 View.OnClickListener click = new View.OnClickListener() {
     @Override
     public void onClick(View view) {
         String thought = mTextThought.getText().toString().trim();
         mFactBook.addFact(thought);
         Toast.makeText(InputActivity.this, "Your thought has been added!!",
                 Toast.LENGTH_LONG).show();
         mTextThought.setText("");

     }
 };

 mSaveButton.setOnClickListener(click);
 }
 }

最佳答案

我认为您的代码有问题。 addFact代码不应该是这样的:

public void addFact(String thought) {
        mFacts.addFact(thought);
};

08-18 05:13
查看更多