将文本从一个活动添加到另一个活动的错误

时间:2019-05-02 21:59:42

标签: java android kotlin

我想制作一个简单的应用程序,您可以在一个活动中在editText上键入文本,而在另一个活动中将其写在listView上。但是我遇到了一个问题,当我添加文本时什么也没有发生,当我单击应该传递文本的列表时,我的应用程序崩溃了。

class MainActivity : AppCompatActivity() {
    private val ADD_WORD_STUPID_CODE = 1931
    private val defns = ArrayList <String>()
    private lateinit var adapter : ArrayAdapter<String>

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        readDictionaryFile()
        setupList()
        definitions.setOnItemClickListener{_,_,index,_  ->
            defns.removeAt(index)
        }
    }
    private fun readDictionaryFile(){
        val reader = Scanner(resources.openRawResource(R.raw.reci))
        while (reader.hasNextLine()){
            val line = reader.nextLine()
            Log.d("Marty", "the next line is $line")
        }
    }
    private fun setupList(){
        //pick random word
        val list = ArrayList<String>()
        list.add("Hello")
        list.add("Wasupp")
        list.add("Mihajlo")


        val rand = Random()
        val index = rand.nextInt(list.size)
        val wordSecond= list[index]
        word.text = wordSecond

        //pick random definiton of the word
        defns.add("A greetings")
        defns.add("Gangsta way for hello")
        defns.add("Another")
        defns.add("World")
        defns.add("Earth")

        adapter = ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, defns)
        adapter.notifyDataSetChanged()
        definitions.adapter = adapter



    }
    fun activtyStart (view: View){
        val myIntent = Intent(this, addWordActivity::class.java)
        startActivityForResult(myIntent, ADD_WORD_STUPID_CODE)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, myIntent: Intent?) {
        if (requestCode == ADD_WORD_STUPID_CODE){
            if (myIntent != null) {
                var wordss = myIntent.getStringExtra("word")
                defns.add(wordss)
                }
        }

    }

在第二次活动中向我们鸣叫

    }private val wordFile = "reci.txt"
        fun addWordButton (view: View){
            var addWord = wordAdd.text.toString()
            val outStream = PrintStream(openFileOutput(wordFile, Context.MODE_PRIVATE))
            outStream.println(addWord)
            outStream.close()
            // go back to the main activity, and return word to them
            val myIntent = Intent()
            myIntent.putExtra("addword", addWord)
            setResult(Activity.RESULT_OK, myIntent)
            finish()
    }
}

2 个答案:

答案 0 :(得分:0)

问题是您应该在onactivityresult中的getstringextra中使用“ addword”作为键。否则,您将为defns添加null。

答案 1 :(得分:0)

您在putextras中使用addword并通过单词调用它的键中的错误

var wordss = myIntent.getStringExtra("word")

 myIntent.putExtra("addword", addWord)