Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
176 views
in Technique[技术] by (71.8m points)

android - How to use shared preferences to update data from another activity?

I have two activities A and B. A is the homepage and when the plus button is clicked it goes to B where there are two edit texts (question and answer). When both are inputted it and the check button is clicked, it is taken back to A where a new button appears with the text set to the inputted question. I have an inflated view which allows the user to edit the question and answer when clicking the button. The problem is that when I use finish() on activity B, it destroys it. I want to use shared preferences on activity A to save the inputted texts on question B but I have no idea how. Can anyone please help?

Activity A:

    package com.example.uh

import android.app.Activity
import android.app.AlertDialog
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.graphics.Color
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.Gravity
import android.widget.Button
import android.widget.LinearLayout
import com.google.android.material.floatingactionbutton.FloatingActionButton

class MainActivity : AppCompatActivity() {
    lateinit var preferences: SharedPreferences
    private val questionActivityCode = 2
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        findViewById<FloatingActionButton>(R.id.btn2).setOnClickListener{
            startActivityForResult(Intent(this@MainActivity, SecondActivity::class.java), questionActivityCode)
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)

        if (requestCode == questionActivityCode && resultCode == Activity.RESULT_OK) {
            createNewButtonWithText(data?.getStringExtra("test") ?: "")
        }
    }

    private fun createNewButtonWithText(text: String)
    {
        val newbutton = Button(this@MainActivity)
        val layout = findViewById<LinearLayout>(R.id.mainlayout)
        newbutton.text = text
        newbutton.layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT)
        newbutton.width=1010
        newbutton.height=300
        newbutton.gravity = Gravity.CENTER
        newbutton.translationX= 65F
        newbutton.setTextColor(Color.parseColor("#FFFFFFFF"))
        newbutton.setBackgroundColor(Color.parseColor("#250A43"))
        layout.addView(newbutton)

        val inflator = layoutInflater
        val builder = AlertDialog.Builder(this)
        val intent = Intent(this@MainActivity, SecondActivity::class.java)

        preferences = getSharedPreferences("SHARED_PREF", Context.MODE_PRIVATE)
        val question = preferences.getString("text", "")
        val answer = preferences.getString("text2", "")
        if (question != null && answer != null) {
        //?
        }
        else{
        //?
        }

        newbutton.setOnClickListener{
            val dialogLayout = inflator.inflate(R.layout.text, null)
                    with(builder) {
                        setTitle(newbutton.text)
                        setPositiveButton("Edit"){dialog, which ->
                            startActivity(intent)
                        }
                        setNegativeButton("Cancel"){dialog, which ->
                            Log.d("Main", "Negative button clicked")
                        }
                        setView(dialogLayout)
                        show()
                    }
        }
    }}

Activity B:

    package com.example.uh

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.content.SharedPreferences
import android.os.Bundle
import android.widget.EditText
import androidx.appcompat.app.AppCompatActivity
import com.google.android.material.floatingactionbutton.FloatingActionButton

class SecondActivity : AppCompatActivity() {
    lateinit var sharedPreferences: SharedPreferences
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_second)


        val question = findViewById<EditText>(R.id.question)
        val answer = findViewById<EditText>(R.id.answer)

        sharedPreferences = getSharedPreferences("SHARED_PREF", Context.MODE_PRIVATE)

        findViewById<FloatingActionButton>(R.id.btn3).setOnClickListener {
            val questiontext = question.text.toString()
            val answertext = answer.text.toString()
            val editor:SharedPreferences.Editor = sharedPreferences.edit()
            editor.putString("text", questiontext)
            editor.putString("text2", answertext)
            editor.apply()


            val returnIntent = Intent()
            returnIntent.putExtra("test", questiontext)
            setResult(Activity.RESULT_OK, returnIntent)

            finish()
        }
    }

}
question from:https://stackoverflow.com/questions/65600631/how-to-use-shared-preferences-to-update-data-from-another-activity

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Right after your sharedPreferences line, you can use it to set the initial text of the two views and have it default to an empty String if nothing has been set yet (e.g. the first time the second Activity is opened).

sharedPreferences = getSharedPreferences("SHARED_PREF", Context.MODE_PRIVATE)
question.setText(sharedPreferences.getString("text", ""))
answer.setText(sharedPreferences.getString("text2", ""))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...