Редактировать теги SharedPreferences в Android с помощью Kotlin - PullRequest
0 голосов
/ 27 февраля 2019

Я создаю приложение, которое принимает запрос и тег.Каждый раз, когда кто-то нажимает кнопку сохранения, он создает новую кнопку с тегом, содержащим запрос.Существует возможность отредактировать запрос и сохранить его.

Каждый раз, когда я пытаюсь отредактировать имя кнопки, вместо изменения имени я получаю новую кнопку.Я использую SharedPreferences для хранения этой информации, и я пытаюсь редактировать ее, но я все еще не уверен, содержит ли она точную информацию, такую ​​как массив, чтобы я мог обновить GUI.Я чувствую, что упускаю что-то очевидное, но просто не могу понять, что это.

MainActivity.kt

class MainActivity : AppCompatActivity() {

    //contain the user's saved feeds
    private var savedFeeds: SharedPreferences? = null
    var tagName:String = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        savedFeeds = this.getSharedPreferences("feeds", Context.MODE_PRIVATE)

        //register listeners for the Save and Clear Tags buttons
        saveButton.setOnClickListener{handleSaveButtonClick()}
        clearTagsButton.setOnClickListener{handleClearTagsButtonClick()}
Log.d("tag", "logging")
        //add previously saved feeds to the GUI
        refreshButtons(null)
    }

    fun copyTag (tag:String): String {
        tagName = tag
        Log.d("TAGClass",tagName)
        return tagName
    }
    //recreate search tag and edit buttons for all saved feeds
    //pass null to create all of them
    private fun refreshButtons(newTag:String?) {
        //store the saved tags in the tags array
        val tags: Array<String> = savedFeeds!!.all.keys.toTypedArray()
        tags.sortWith(String.CASE_INSENSITIVE_ORDER) //sort by tag
        //if a new tag is being added, insert into the GUI at the appropriate location
        if (newTag != null && newTag != tagName) {
            var index = tags.binarySearch(newTag!!)
            if (index < 0) index = -index-1
            makeTagGUI(newTag!!, index)
        }
        else{
            //display all feeds
            for (index in tags.indices)
                makeTagGUI(tags[index],index)
        }
    }

    //add a new search to the saved feeds, then refresh all the button
    private fun makeTag(query:String, tag:String) {
        //original query will be "" if we have a new search
        //getString looks up the previous value associated with tag if any
        //if no value is found, the second arg is returned
        val originalQuery = savedFeeds!!.getString(tag,"")

        //get a SharedPreferences.Editor so we can store the new tag/query or
        //the updated one
        val editor = savedFeeds!!.edit()
        editor.putString(tag, query)
        editor.apply() //store the preferences - updates the file



        //or
        //savedFeeds!!.edit().putString(tag,query).apply()

        //if new query add to GUI
        if (originalQuery == "") {
            refreshButtons(tag)
        }

    } //makeTag

    //add a new button and corresponding edit button to the GUI
    private fun makeTagGUI(tag:String, index: Int) {
        //inflate new_tag_view layout
        val inflater = LayoutInflater.from(applicationContext)
        val newTagView = inflater.inflate(R.layout.new_tag_view,null,false)

        //get newTagButton and set its text and register listener
        val newTagButton = newTagView.findViewById<Button>(R.id.newTagButton)
        newTagButton.text = tag


        newTagButton.setOnClickListener(object: View.OnClickListener{
            override fun onClick(v: View?) {
                handleQueryButtonClicked(v!! as Button)
            }
        })

        //get newTagButton and set its text and register listener
        val newEditButton = newTagView.findViewById<Button>(R.id.newEditButton)
        newEditButton.setText(R.string.edit)
        newEditButton.setOnClickListener(object: View.OnClickListener{
            override fun onClick(v: View?) {
                handleEditButtonClicked(v!! as Button)
                //val tagValue = copyTag(tag)
                Log.d("Buttontag", tagName)
            }
        })

        //add them to the layout
        queryLinearLayout.addView(newTagView,index)


    } //maketaggui

    //remove all the saved searches
    private fun clearButtons() {
        queryLinearLayout.removeAllViews()
    }

    //for save button clicks
    private fun handleSaveButtonClick() {
        //create a tag if both the queryEditText and tagEditText are not empty
        if (queryEditText.text.length > 0 &&
                tagEditText.text.length > 0 ) {

            makeTag(queryEditText.text.toString(),
                    tagEditText.text.toString())
            //val copiedTag = copyTag(tagEditText.text.toString())
            Log.d("TAGGED", tagName + "saveButtonClick")

            //clear text
            queryEditText.setText("")
            tagEditText.setText("")

            //dismiss the keyboard
            (getSystemService(Activity.INPUT_METHOD_SERVICE) as
                    InputMethodManager).hideSoftInputFromWindow(tagEditText.windowToken,0)

        }
        else if (queryEditText.text.length < 0 &&
                tagEditText.text.toString() == tagName)
        {

        }
        else {
            //display a message
            val builder = AlertDialog.Builder(this@MainActivity)
            builder.setTitle(R.string.missingTitle) //title bar

            //ok button to dismiss the alert
            builder.setPositiveButton(R.string.OK,null)

            builder.setMessage(R.string.missingMessage) //message

            //create the dialog
            val errorDialog:AlertDialog = builder.create()
            errorDialog.show()

        }
    }

    //for each of the tag buttons, open a browser to view the feed
    private fun handleQueryButtonClicked(v: Button) {

        //get query
        val buttonText = v.text.toString()
        //val copiedTag = copyTag(v.text.toString())
        Log.d("TAG", tagName + "handleQuery")
        val query = savedFeeds!!.getString(buttonText,"")

        //create the url
        val urlString = getString(R.string.searchURL)+query
        Log.d("TAG",urlString)

        //create an intent to launch a browser
        val webIntent = Intent(Intent.ACTION_VIEW,
                    Uri.parse(urlString))

        startActivity(webIntent) //execute the intent
    }

    //handle edit button
    private fun handleEditButtonClicked(v: Button) {
        //get all necessary GUI components
        val buttonRow = v.parent as ConstraintLayout
        val searchButton = buttonRow.findViewById<Button>(R.id.newTagButton)
        val tag = searchButton.text.toString()

        val copiedTag = copyTag(tag)
        Log.d("TAG", tagName + "handleEdit")


        //set the edittexts to match the chosen tag and query
        tagEditText.setText(tag)
        queryEditText.setText(savedFeeds!!.getString(tag,""))
    }

    //handle the clear button
    private fun handleClearTagsButtonClick() {
        val builder = AlertDialog.Builder(this@MainActivity)
        builder.setTitle(R.string.confirmTitle)

        builder.setPositiveButton(R.string.erase) { dialog, which ->
            clearButtons()
            savedFeeds!!.edit().clear().apply()
        }

        builder.setCancelable(true)
        builder.setNegativeButton(R.string.cancel, null)

        builder.setMessage(R.string.confirmMessage)

        builder.create().show()
    }

} //class

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">
    <EditText
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:inputType="textPersonName"
            android:ems="10"
            android:id="@+id/queryEditText"
            android:hint="@string/queryPrompt" android:imeOptions="actionNext" android:layout_marginEnd="8dp"
            app:layout_constraintEnd_toEndOf="parent" android:layout_marginStart="8dp"
            app:layout_constraintStart_toStartOf="parent" android:layout_marginTop="8dp"
            app:layout_constraintTop_toTopOf="parent"/>
    <EditText
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:inputType="textPersonName"
            android:ems="10"
            android:id="@+id/tagEditText"
            android:hint="@string/tagPrompt" android:imeOptions="actionDone"
            android:layout_marginStart="8dp"
            app:layout_constraintStart_toStartOf="parent" android:layout_marginTop="8dp"
            app:layout_constraintTop_toBottomOf="@+id/queryEditText"/>
    <Button
            android:text="@string/save"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/saveButton" android:textStyle="bold"
            android:textSize="18sp" app:layout_constraintStart_toEndOf="@+id/tagEditText"
            android:layout_marginStart="8dp" android:layout_marginEnd="8dp" app:layout_constraintEnd_toEndOf="parent"
            android:layout_marginTop="8dp" app:layout_constraintTop_toBottomOf="@+id/queryEditText"/>
    <Button
            android:text="@string/clearTags"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:id="@+id/clearTagsButton" app:layout_constraintEnd_toEndOf="parent" android:layout_marginEnd="8dp"
            app:layout_constraintStart_toStartOf="parent" android:layout_marginStart="8dp"
            android:layout_marginBottom="8dp" app:layout_constraintBottom_toBottomOf="parent"/>
    <ScrollView
            android:layout_width="0dp"
            android:layout_height="0dp"
            app:layout_constraintStart_toStartOf="parent" android:layout_marginStart="8dp"
            android:layout_marginEnd="8dp" app:layout_constraintEnd_toEndOf="parent" android:layout_marginTop="8dp"
            app:layout_constraintTop_toBottomOf="@+id/tagEditText" android:layout_marginBottom="8dp"
            app:layout_constraintBottom_toTopOf="@+id/clearTagsButton" android:background="@color/light_orange">
        <LinearLayout
                    android:id="@+id/queryLinearLayout"
                    android:layout_width="match_parent"
                      android:layout_height="match_parent"
                      android:orientation="vertical"/>
    </ScrollView>
</androidx.constraintlayout.widget.ConstraintLayout>

new_tagview.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
                                                   xmlns:app="http://schemas.android.com/apk/res-auto"
                                                   xmlns:tools="http://schemas.android.com/tools"
                                                   android:layout_width="match_parent"
                                                   android:layout_height="wrap_content" android:id="@+id/newTagRow"
                                                   android:background="@android:color/transparent">

    <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content" android:id="@+id/newTagButton"
            app:layout_constraintStart_toStartOf="parent" app:layout_constraintHorizontal_bias="0.5"
            app:layout_constraintEnd_toStartOf="@+id/newEditButton"
            app:layout_constraintHorizontal_chainStyle="spread_inside" app:layout_constraintTop_toTopOf="parent"/>
    <Button
            android:text="@string/edit"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/newEditButton"
            app:layout_constraintStart_toEndOf="@+id/newTagButton" app:layout_constraintHorizontal_bias="0.5"
            app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toTopOf="parent"/>
</androidx.constraintlayout.widget.ConstraintLayout>

Ответы [ 2 ]

0 голосов
/ 01 марта 2019

Что я сделал, так это то, что вы не можете вызывать refreshButtons (null) прямо в текущем макете ограничения.

Вы должны добавлять и удалять объекты из SharedPreferences, используя .remove, и обновлять текущий графический интерфейс.

0 голосов
/ 27 февраля 2019

изменяет этот код

private var savedFeeds: SharedPreferences? = null

на

private val sharedPreferences = PreferenceManager.getDefaultSharedPreferences(contex)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...